获取包含字符串的行号

时间:2012-03-30 16:18:47

标签: vb.net text numbers line

如何获取包含文本文件中指定字符串的行号?

示例文本文件包含:

  


  白
  黄
  绿色

如何获得“黄色”行号?我可以在指定的行中写一个字符串,假设我想在第2行写一个字符串吗?

3 个答案:

答案 0 :(得分:1)

Dim toSearch = "Yellow"
Dim lineNumber = File.ReadLines(filePath).
                 Where(Function(l) l.Contains(toSearch)).
                 Select(Function(l, index) index)

If lineNumber.Any Then 
    Dim firstNumber = lineNumber.First
End If

编辑:如果您想在该行中写一个字符串,最好的方法是用新的一行替换该行。在下面的例子中,我用“Yellow Submarine”替换所有出现的“Yellow”

Dim replaceString = "Yellow Submarine"
Dim newFileLines = File.ReadLines(filePath).
                   Where(Function(l) l.Contains(toSearch)).
                   Select(Function(l) l.Replace(toSearch, replaceString))
File.WriteAllLines(path, newFileLines)

或者您想要替换特定的行:

Dim allLines = File.ReadAllLines(path)
allLines(lineNumber) = replaceString 
File.WriteAllLines(path, allLines)

答案 1 :(得分:1)

要在文本文件中查找一行,您需要从文件开头读取行,直到找到它为止:

string fileName = "file.txt";
string someString = "Yellow";

string[] lines = File.ReadAllLines(fileName);
int found = -1;
for (int i = 0; i < lines.Length; i++) {
  if (lines[i].Contains(someString)) {
    found = i;
    break;
  }
}

如果要更改文件中的行,则必须读取整个文件并使用更改的行将其写回:

string[] lines = File.ReadAllLines(fileName);
lines[1] = "Black";
File.WriteAllLines(fileName, lines);

答案 2 :(得分:0)

Imports System.IO

Dim int1 As Integer
Dim path As String = "file.txt"
Dim reader As StreamReader

Public Sub find()
    int1 = New Integer
    reader = File.OpenText(path)
    Dim someString As String = Form1.TextBox1.Text 'this Textbox for searching text example : Yellow
    Dim lines() As String = File.ReadAllLines(path)
    Dim found As Integer = -1
    Dim i As Integer
    For i = 0 To lines.Length - 1 Step i + 1
        If lines(i).Contains(someString) Then
            found = i
            int1 = i
            Exit For
        End If
    Next
    reader = File.OpenText(path)

    'if you want find same word then

    Dim lines2() As String = File.ReadAllLines(path)
    Form1.ListBox1.Items.Add(lines2(int1))
    int1 = New Integer
End Sub