在文本文件中搜索特定单词并显示其所在的行

Searching for a Specific Word in a Text File and Displaying the line its on

我在使用 C# 尝试在文本文件中查找单词时遇到问题。

我想找到输入到控制台的单词,然后在控制台 中显示找到该单词的整行。

在我的文本文件中有:

斯蒂芬·哈伦,12 月,9,4055551235

Laura Clausing,一月,23,4054447788

威廉·康纳,12 月 13 日,123456789

卡拉玛丽,十月,23,1593574862

奥黛丽·卡瑞特,一月,16,1684527548

塞巴斯蒂安贝克,十月,23,9184569876

所以如果我输入 "December" 我希望它显示 "Stephen Haren,December,9,4055551235" 和 "William Connor,December,13,123456789" .

我考虑过使用子字符串,但我认为必须有更简单的方法。

给出答案后我的代码:

using System;
using System.IO;
class ReadFriendRecords
{
    public static void Main()
    {
        //the path of the file
        FileStream inFile = new FileStream(@"H:\C#\Chapter.14\FriendInfo.txt", FileMode.Open, FileAccess.Read);
        StreamReader reader = new StreamReader(inFile);
        string record;
        string input;
        Console.Write("Enter Friend's Birth Month >> ");
        input = Console.ReadLine();
        try
        {
            //the program reads the record and displays it on the screen
            record = reader.ReadLine();
            while (record != null)
            {
                if (record.Contains(input))
                {
                    Console.WriteLine(record);
                }
                    record = reader.ReadLine();
            }
        }
        finally
        {
            //after the record is done being read, the progam closes
            reader.Close();
            inFile.Close();
        }
        Console.ReadLine();
    }
}

遍历所有行(StreamReader、File.ReadAllLines 等)并检查是否 line.Contains("December")(将 "December" 替换为用户输入)。

编辑: 如果您有大文件,我会选择 StreamReader。并使用来自@Matias Cicero 的 IndexOf-Example 而不是 contains 不区分大小写。

Console.Write("Keyword: ");
var keyword = Console.ReadLine() ?? "";
using (var sr = new StreamReader("")) {
    while (!sr.EndOfStream) {
        var line = sr.ReadLine();
        if (String.IsNullOrEmpty(line)) continue;
        if (line.IndexOf(keyword, StringComparison.CurrentCultureIgnoreCase) >= 0) {
            Console.WriteLine(line);
        }
    }
}

这样的事情怎么样:

//We read all the lines from the file
IEnumerable<string> lines = File.ReadAllLines("your_file.txt");

//We read the input from the user
Console.Write("Enter the word to search: ");
string input = Console.ReadLine().Trim();

//We identify the matches. If the input is empty, then we return no matches at all
IEnumerable<string> matches = !String.IsNullOrEmpty(input)
                              ? lines.Where(line => line.IndexOf(input, StringComparison.OrdinalIgnoreCase) >= 0)
                              : Enumerable.Empty<string>();

//If there are matches, we output them. If there are not, we show an informative message
Console.WriteLine(matches.Any()
                  ? String.Format("Matches:\n> {0}", String.Join("\n> ", matches))
                  : "There were no matches");

这种方法简单易读,它使用 LINQ and String.IndexOf instead of String.Contains 因此我们可以进行不区分大小写的搜索。

如@Rinecamo 所述,试试这个代码:

string toSearch = Console.ReadLine().Trim();

在此代码行中,您将能够读取用户输入并将其存储在一行中,然后对每一行进行迭代:

foreach (string  line in System.IO.File.ReadAllLines(FILEPATH))
{
    if(line.Contains(toSearch))
        Console.WriteLine(line);
}

FILEPATH替换为绝对路径或相对路径,例如".\file2Read.txt".

要在文件中查找文本,您可以使用此算法在

中使用此代码
static void Main(string[] args)
    {
    }

试试这个

StreamReader oReader;
if (File.Exists(@"C:\TextFile.txt")) 
{
Console.WriteLine("Enter a word to search");
string cSearforSomething = Console.ReadLine().Trim();
oReader = new StreamReader(@"C:\TextFile.txt");
string cColl = oReader.ReadToEnd();
string cCriteria = @"\b"+cSearforSomething+@"\b";
System.Text.RegularExpressions.Regex oRegex = new 
System.Text.RegularExpressions.Regex(cCriteria,RegexOptions.IgnoreCase);

int count = oRegex.Matches(cColl).Count;
Console.WriteLine(count.ToString());
}
Console.ReadLine();