如何解决VB.net从开头为文本文件中读取特定行,并在开头时停止读取
我希望从文本文件中读取以某些字符开头的行,并在该行以其他字符开头时停止。因此,在我的示例中,我想从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处读取。我尝试过“做一会儿”和“做直到”,但没有成功。有什么建议吗?
解决方法
您可以使用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,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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。