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

后端 未结 4 682
小鲜肉
小鲜肉 2020-12-31 19:13

I am having trouble attempting to find words in a text file in C#.

I want to find the word that is input into the console then display the entire line that the word

4条回答
  •  感情败类
    2020-12-31 19:35

    How about something like this:

    //We read all the lines from the file
    IEnumerable 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 matches = !String.IsNullOrEmpty(input)
                                  ? lines.Where(line => line.IndexOf(input, StringComparison.OrdinalIgnoreCase) >= 0)
                                  : Enumerable.Empty();
    
    //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");
    

    This approach is simple and easy to read, it uses LINQ and String.IndexOf instead of String.Contains so we can do a case insensitive search.

提交回复
热议问题