作为我在VB.net中构建的应用程序的一部分,我正在尝试导入多个txt文件,并能够计算该文件的多少行以特定数字开头(例如1)并显示它在消息框中。
到目前为止,这是我的代码:
OpenFileDialog1.DefaultExt = "txt"
OpenFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
For Each File In OpenFileDialog1.FileNames
My.Computer.FileSystem.ReadAllText(OpenFileDialog1.FileName)
For Each fileName In OpenFileDialog1.FileNames
For Each line As String In System.IO.File.ReadLines(fileName)
Dim Linecount = line.count
If line.StartsWith("1") Then
MsgBox(LineCount)
End If
Next
Next
Next
上面的代码不起作用,因为它给了我错误的行数。在我的txt文件中,我只有一行以“1”开头。
答案 0 :(得分:0)
您只是在这里显示每行中的字符数:
For Each line As String In System.IO.File.ReadLines(fileName)
Dim Linecount = line.Count ' Number of characters
您可以使用LINQ获取以1开头的行数:
Dim lineWithOne = File.ReadLines(fileName).Count(Function(l) l.StartsWith("1"))
如果您不想或不能使用LINQ,这是一种经典的方式:
Dim lineWithOne = 0
For Each line As String In System.IO.File.ReadLines(fileName)
If line.StartsWith("1") Then lineWithOne += 1
Next