在文本文件中搜索关键字

时间:2017-09-03 11:43:47

标签: .net vb.net

我必须编写一个程序,要求用户输入一个关键字,之后它应该打开一个文本文件,并在每个包含该关键字的行中写入控制台。

我需要使用.Contains()方法搜索特定字符串中的文本。被搜索的文本应作为参数传递。"

到目前为止我所拥有的是:

    Sub Main()
       Console.Write("Please enter a keyword: ")
       Dim keyword As String = Console.ReadLine()

       Dim filePath As String = "C:\...\Projects\testing.txt"
       Dim fileHolder As System.IO.StreamReader
       Dim sentence As String
       fileHolder = My.Computer.FileSystem.OpenTextFileReader(filePath)
       sentence = fileHolder.ReadLine()

任何提示或提示都会有所帮助。谢谢!

1 个答案:

答案 0 :(得分:2)

尝试这样的事情:

URLEncodedUtils

你也可以这样做而不用像这样循环:

Console.Write("Please enter a keyword: ")
Dim keyword As String = Console.ReadLine()

Dim filePath As String = "C:\a.txt"
Dim lines() As String = System.IO.File.ReadAllLines(filePath)
For i = 0 To lines.Length - 1
    If lines(i).Contains(keyword) Then Console.WriteLine(lines(i))
Next
Console.ReadKey()

此代码也可缩短为:

Console.Write("Please enter a keyword: ")
Dim keyword As String = Console.ReadLine()

Dim filePath As String = "C:\a.txt"
Dim lines() As String = System.IO.File.ReadAllLines(filePath)
Dim filteredLines As String = String.Join(vbNewLine, lines.Where(Function(line As String) line.Contains(keyword)).ToArray())
Console.WriteLine(filteredLines)
Console.ReadKey()