0

我希望从文本文件中读取以某些字符开头的行,并在该行以其他字符开头时停止。因此,在我的示例中,我想从 AB 行开始阅读并在 EF 行停止,但并非所有行都包含 CD 行。总会有 AB 线和 EF 线,但其间的线数未知。

这是我将要阅读的文本文件中的行示例。您可以看到这将在 DataGridView 中创建两行,但是第一行缺少 CD 行并且应该是空白的。

AB-id1
EF-address1
AB-id2
CD-name1
EF-address2

这是我到目前为止的代码:

  Dim lines() As String = File.ReadAllLines(textfile)
    For i As Integer = 0 To lines.Length - 1
            If lines(i).StartsWith("AB") Then
            Dim nextLines As String() = lines.Skip(i + 1).ToArray
            
            Dim info As String = nextLines.FirstOrDefault(Function(Line) Line.StartsWith("CD"))
            Dim name As String = "Yes"
            
            Dim info2 As String = nextLines.FirstOrDefault(Function(Line) Line.StartsWith("EF"))
            Dim address As String = "Yes"
            End If

            DataGridView.Rows.Add(name,address)
    Next 

现在我目前得到的输出是:

|Yes|Yes|
|Yes|Yes|

我应该得到:

||Yes|
|Yes|Yes|

看起来它在文本文件中读取得太远了,我需要它在 EF 处停止读取。我试过 Do while 和 Do until 没有成功。有什么建议么?

4

1 回答 1

0

您可以使用Array.FindIndex函数来获取以您的前缀开头的下一行的索引。这样您就不必每次都跳过行并创建一个新数组。

试试这个:

Dim lines() As String = File.ReadAllLines(textFile)
For i As Integer = 0 To lines.Length - 1
    If lines(i).StartsWith("AB") Then
        Dim addressIndex As Integer = Array.FindIndex(lines, i + 1, Function(Line) Line.StartsWith("EF"))
        Dim address As String = If(addressIndex <> -1, lines(addressIndex).Substring(3), "") ' Get everything past the "-"

        Dim name As String = ""
        If addressIndex <> -1 Then
            Dim nameIndex As Integer = Array.FindIndex(lines, i + 1, addressIndex - i, Function(line) line.StartsWith("CD"))
            If nameIndex <> -1 Then
                name = lines(nameIndex).Substring(3) ' Get everything past the "-"
            End If
        End If

        DataGridView.Rows.Add(name, address)
    End If
Next
于 2020-11-11T19:06:59.040 回答