Get line number that contains a string

2019-08-30 05:33发布

How to get a line number that contains a specified string in a text file?

Example text file contains:

Red
White
Yellow
Green

How to get "Yellow" line number? and can i write a string in a specified line, lets say i want to write a string in line 2?

3条回答
狗以群分
2楼-- · 2019-08-30 05:57
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

Edit: If you want to write a string in that line, the best way would be to replace that line with the new one. In the following example i'm replacing all occurences of "Yellow" with "Yellow Submarine"

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)

Or you want to replace a specific line:

Dim allLines = File.ReadAllLines(path)
allLines(lineNumber) = replaceString 
File.WriteAllLines(path, allLines)
查看更多
地球回转人心会变
3楼-- · 2019-08-30 06:02

To find a line in a text file, you need to read the lines from the start of the file until you find it:

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;
  }
}

If you want to change a line in a file, you have to read the entire file and write it back with the changed line:

string[] lines = File.ReadAllLines(fileName);
lines[1] = "Black";
File.WriteAllLines(fileName, lines);
查看更多
走好不送
4楼-- · 2019-08-30 06:10
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
查看更多
登录 后发表回答