简体   繁体   English

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

[英]Searching for a word in a text file in C#

I have a small txt file containing three lines of text. 我有一个小的txt文件,其中包含三行文本。 I'm trying to create a programme in C# that gets a word from a user and searches for that word in the txt file. 我正在尝试使用C#创建一个程序,该程序从用户那里得到一个单词,然后在txt文件中搜索该单词。 If the word is found, I'm wanting to record and display what lines of the txt file the word was found on. 如果找到了该单词,我想记录并显示在该单词所在的txt文件的哪些行。 The variable int position records if the word is found or not, but I can't work out how to record what lines the word is found on. 变量int position记录是否找到单词,但是我不知道如何记录单词在哪行。 How would I do this? 我该怎么做? Here is my code: 这是我的代码:

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();
    }
}

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). 您最后打印的位置是错误的,很可能是-1(除非您的最后一个匹配项位于最后一行)。 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 编辑:拼写

This looks like a homework task so I'm only going to give you some hints: 这看起来像是一项家庭作业,所以我只给您一些提示:

  1. Every time you call "myfile.ReadLine()", you have moved to the next line of the file. 每次调用“ myfile.ReadLine()”时,都已移至文件的下一行。 You might want to track how many lines you have read. 您可能需要跟踪已阅读的行数。

  2. To record a list of values, you can use a List<Type> variable. 要记录值列表,可以使用List<Type>变量。

    Example: 例:

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

    Result: 结果:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM