【问题标题】:Search for words in a file. C# [duplicate]在文件中搜索单词。 C# [重复]
【发布时间】:2015-11-28 01:16:47
【问题描述】:

我正在尝试在我正在读入 C# 的文本文件中搜索一个单词。

到目前为止,它一直显示单词在第 0 行,而实际上不是。

我在代码中做错了什么?

另外,我如何让它计算我搜索的单词,以便它可以显示出现的数量?

        string line;
        int counter = 0;

        Console.WriteLine("Enter a word to search for: ");
        var text = Console.ReadLine();

        string file = "newfile.txt";
        StreamReader myFile = new StreamReader(file);

        Console.WriteLine("\n");

        while ( (line = myFile.ReadLine()) != null )
        {
            if(line.Contains(text))
            {
                break;
            }
            counter++;
        }
        Console.WriteLine("Line number: {0}", counter);

        myFile.Close();
        Console.ReadLine();

【问题讨论】:

  • 你确定你的代码正在进入while循环吗?
  • 你到底在做什么?
  • 那么只有1个while循环...
  • 当前目录下是否有名为“newfile.txt”的文件?您是否尝试过提供绝对路径?
  • @AsadSaeeduddin 是的,有一个文件。我能够在 Windows 控制台中显示它。

标签: c# file search io


【解决方案1】:

要解决您问题的另一部分...“如何找到所有出现的事件”。

添加一个新变量来存储找到的数字:

int found = 0;

重做您的 while 循环以不中断 - 但报告您在哪里找到它并增加您找到的计数。在 while 循环之后总结你的发现。

while ((line = myFile.ReadLine()) != null)
{
    // Increment the line counter first so it's not zero indexed
    counter++;

    // If it contains the text tell us what line and increase found
    // Note: No need to break out of the code since we want to find all of them this time
    if (line.Contains(text))
    {
        Console.WriteLine("Found on line number: {0}", counter);
        found++;
    }
}

Console.WriteLine("A total of {0} occurences found", found);

【讨论】:

  • 哦,很好,这就是我编码的目标。一个问题,有没有办法找到一个单词,以及它出现在单词 their 中的次数是多少?
  • 我将如何使它不区分大小写?
  • 您可以编写所有可能的代码来查找这是否是一个完整的单词...例如检查匹配后是否有空格或标点符号(使用IndexOf()Substring())。同样,您可以使用ToLower() 修改字符串的大小写 - 但它开始变得复杂。我建议你看看 RegEx 可以为你做什么......
  • 我正在尝试正则表达式,但它下面有一条红色下划线。我需要添加什么额外的东西才能使用它吗?
  • 添加using System.Text.RegularExpressions;。那里有大量的 RegEx 示例...尝试this URLthis set of examples 以获得一些通用指针。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多