【问题标题】:Searching for a Specific Word in a Text File and Displaying the line its on在文本文件中搜索特定单词并显示其所在的行
【发布时间】:2015-10-21 14:07:55
【问题描述】:

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

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

在我的文本文件中:

斯蒂芬·哈伦,十二月,9,4055551235

Laura Clausing,一月,23,4054447788

William Connor,December,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();
    }
}

【问题讨论】:

标签: c# text-files


【解决方案1】:

遍历所有行(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);
        }
    }
}

【讨论】:

    【解决方案2】:

    正如@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”。

    【讨论】:

      【解决方案3】:

      这样的事情怎么样:

      //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");
      

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

      【讨论】:

        【解决方案4】:

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

        中使用此代码
        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();
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-02-09
          • 2015-02-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-08-28
          相关资源
          最近更新 更多