如何在文本文件中显示字符串? (C#控制台应用程序)

时间:2015-12-01 01:04:35

标签: c# regex io console

所以,我发现了如何显示输入字符串的出现次数,但我不知道如何显示单词的外观以及它所在单词的句子。例如,我的输入字符串是“ “,但是如何在控制台上将其显示为The或THE或枯萎?另外,我如何用它所在的句子显示这个输入字符串?例如:“the”,句子:干旱使公共汽车枯萎。

这是我到目前为止的代码:

static void Main(string[] args)
    {
        string line;
        int counter = 0;

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

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

        int found = 0;

        while ((line = myFile.ReadLine()) != null)
        {
            counter++;
            if (line.IndexOf(userText, StringComparison.CurrentCultureIgnoreCase) != -1)
            {
                Console.WriteLine("Found on line number: {0}", counter);
                found++;
            }
        }
        Console.WriteLine("A total of {0} occurences found", found);
    }

2 个答案:

答案 0 :(得分:0)

如何改变一行:

Console.WriteLine("Line {0}: {1}", counter,line);

顺便说一下,我不太明白你的问题,它是什么意思"在控制台上显示为The或THE或枯萎","显示此输入带有句子的字符串"?

答案 1 :(得分:0)

听起来你希望有一个触发比赛的单词,即使它是你比赛的部分词。

while ((line = myFile.ReadLine()) != null)
{
    counter++;
    int index = line.IndexOf(userText, StringComparison.CurrentCultureIgnoreCase);
    if (index != -1)
    {
        //Since we want the word that this entry is, we need to find the space in front of this word
        string sWordFound = string.Empty;
        string subLine = line.Substring(0, index);
        int iWordStart = subLine.LastIndexOf(' ');
        if (iWordStart == -1)
        {
            //If there is no space in front of this word, then this entry begins at the start of the line
            iWordStart = 0;
        }

        //We also need to find the space after this word
        subLine = line.Substring(index);
        int iTempIndex = subLine.LastIndexOf(' ');
        int iWordLength = -1;
        if (iTempIndex == -1)
        {    //If there is no space after this word, then this entry goes to the end of the line.
            sWordFound = line.Substring(iWordStart);
        }
        else
        {
            iWordLength = iTempIndex + index - iWordStart;
            sWordFound = line.Substring(iWordStart, iWordLength);
        }

        Console.WriteLine("Found {1} on line number: {0}", counter, sWordFound);
        found++;
    }
}

这可能有错误,但应该把你推向正确的方向。此外,如果您包含预期输出,则在您的示例中会有所帮助。

这是我对此代码的期望:

input:
The drought withered the bus.
Luke's father is well known.
The THE ThE

output:
Found The on line number: 1
Found withered on line number: 1
Found the on line number: 1
Found father on line number: 2
Found The on line number: 3
Found THE on line number: 3
Found ThE on line number: 3