簡體   English   中英

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

[英]How to display a string within a text file? (C# Console Application)

因此,我發現了如何顯示輸入字符串的出現次數,但是我不知道如何顯示單詞的外觀以及該單詞所在的句子。例如,我的輸入字符串是“ the”,但是如何將其顯示為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);
    }

如何更改一行:

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

順便說一句,我不太理解您的問題,“將其顯示為The或THE或在控制台上枯萎”,以及“顯示此輸入字符串及其所在的句子”是什么意思?

聽起來您想擁有觸發比賽的單詞,即使它只是比賽的一部分。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM