在C#中搜索文本文件中的单词

时间:2015-08-07 01:13:09

标签: c#

我有一个包含三行文字的小文本文件。我试图在C#中创建一个程序,它从用户那里获取一个单词并在txt文件中搜索该单词。如果找到该单词,我想要记录并显示找到该单词的txt文件的哪些行。变量int位置记录是否找到了单词,但是我不知道如何记录找到单词的行。我该怎么做?这是我的代码:

class Program {
    static void Main(string[] args) {
        Console.Write("please enter a file to search for");
        string fileResponse = Console.ReadLine();
        Console.Write("please enter a word to search for in the file");
        string wordResponse = Console.ReadLine();
        StreamReader myfile = File.OpenText(fileResponse);
        string line = myfile.ReadLine();
        int position = line.IndexOf(wordResponse);
        int count = 0; //counts the number of times wordResponse is found.
        int lineNunmber = 0;

            while (line != null) {
                if (position != -1) {
                    count++;
                }
                line = myfile.ReadLine();
            }
         if (count == 0) {
            Console.WriteLine("your word was not found!");
         } else {
            Console.WriteLine("Your word was found " + count + " times!" + position);
         }
         Console.ReadLine();
    }
}

2 个答案:

答案 0 :(得分:2)

I'm assuming you want to print the matching lines and the associate line number. Currently you only remember the number of times you matched. The position you print at the end is wrong, and most likely -1 (unless your last match is on the last line). If you don't need to do anything else with the matches, easiest way would be to print when you find it.

(Also, you're not closing the file you're opening)

using (StreamReader myFile = File.OpenText(fileResponse))
{
    int count = 0; //counts the number of times wordResponse is found.
    int lineNumber = 0;
    while(!myFile.EndOfStream)
    {
        string line = myFile.ReadLine();
        lineNumber++;
        int position = line.IndexOf(wordResponse);
        if (position != -1) {
            count++;
            Console.WriteLine("Match #{0} {1}:{2}", count, lineNumber, line)  
        }
}

if (count == 0) {
    Console.WriteLine("your word was not found!");
} else {
    Console.WriteLine("Your word was found " + count + " times!");
}
Console.ReadLine();

edit:spelling

答案 1 :(得分:0)

这看起来像是一项家庭作业,所以我只会给你一些提示:

  1. 每次调用“myfile.ReadLine()”时,都已移至文件的下一行。您可能想跟踪已阅读的行数。

  2. 要记录值列表,您可以使用List<Type>变量。

    示例:

    // Create the list
    List<int> myListOfIntegers = new List<int>();
    
    // Add some values
    myListOfIntegers.Add(2);
    myListOfIntegers.Add(5);
    myListOfIntegers.Add(3);
    
    // Iterate through the list
    foreach(int item in myListOfIntegers)
    {
        Console.WriteLine("Item Value: " + item);
    }
    

    结果:

    Item Value: 2
    Item Value: 5
    Item Value: 3