使用InStr在VB.NET字符串变量中查找换行符位置

4
我有一个VB.NET应用程序,从数据库中获取字符串数据。这个字符串包含以下数据:

"This is the update:
I have an issue with the application"

我只需要其中的一部分数据,即换行后面的"I have an issue with the application"。

为此,我尝试使用InStr搜索字符串在新行中的位置。我尝试了很多选项,但它们都不起作用。

我使用了"vbCrLf"、Chr(13)、"\r\n"、"\n"、"<br/>"和Environment.NewLine,但它们都不起作用。

我该如何获得所需的数据?

你引用了 vbCrLf 吗?它应该不带引号使用。 - ba__friend
4个回答

2

换行符可以用换行符(Chr(10))或回车/换行符对(Chr(13) + Chr(10))表示。当然,根据数据源的不同,这可能会有所变化。一种实现方法是在这两个字符上进行字符串拆分,并选择删除空元素,丢弃第一个元素,并将其他元素在它们之间使用换行符连接起来:

ReadOnly separators As Char() = New Char() {Chr(10), Chr(13)}
Private Function StripFirstLine(ByVal input As String) As String
    Dim parts() As String = input.Split(separators, StringSplitOptions.RemoveEmptyEntries)

    If parts.Length > 1 Then
        Return String.Join(Environment.NewLine, parts, 1, parts.Length - 1)
    Else
        Return input
    End If

End Function

1
这是CR+LF(Char(13)+ Char(10)),而不是反过来。 - Guffa
@Guffa:你当然是对的;我把它搞反了。一定是天气太热了。 - Fredrik Mörk
4
在vb.net中,你也可以使用单独的vbCr和vbLf常量,而无需调用Chr()函数。 - Joel Coehoorn

2

使用 vbCrLf 而不是 "vbCrLf"。

也可能只有换行符或回车符,因此使用 Chr(10) 和 Chr(13) 也可能是更好的选择。


1

这个脚本将字符串按行返回,然后添加到列表框中:

    Dim fileContents As String
    fileContents = My.Computer.FileSystem.ReadAllText("d:\a.txt")
    TextBox2.Text = fileContents
    Dim a As Integer = 1

    For i = 1 To fileContents.Length
        Dim xx As String = Mid(fileContents, i, 1)
        If xx = Chr(10) Then
            If Mid(fileContents, i - 1, 1) = Chr(13) Then
                ListBox1.Items.Add(Mid(fileContents, a, (i - a) - 1))
                a = i
            End If
        End If
    Next

1

我觉得我对这个讨论没有太多的贡献,但是说句实话...你也可以使用"ControlChars",例如"ControlChars.CrLf"。

MSDN上的ControlChars


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接