如何显示字符串

时间:2015-11-30 01:40:12

标签: c# string while-loop io

我正在处理一个搜索输入文本文件(我选择的)的小代码。我正在创建一个搜索功能。到目前为止,我得到它显示文本文件中出现的搜索词的次数以及行号。我需要一些帮助来显示搜索到的单词在文本文件中的显示方式。例如,如果我搜索单词“the”并在文本文件中显示为“THE”或“The”,我想在控制台窗口中显示它。

感谢任何帮助,建议或建议。提前谢谢!

这是我的代码:

string line;
int counter = 0;

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

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

int found = 0;

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

3 个答案:

答案 0 :(得分:1)

您可以使用IndexOf而不是Contains,因为您想要进行不区分大小写的搜索:

if (line.IndexOf(userText, StringComparison.CurrentCultureIgnoreCase) != -1)
{
    Console.WriteLine("Found on line number: {0}", counter);
    found++;
}

答案 1 :(得分:1)

这可能会为你做到这一点

While ((line = myFile.ReadLine()) != null)
{
    line = line.toUpper();
    counter++;
    if (line.Contains(userText.toUpper()))
    {
        Console.WriteLine("Found on line number: {0}", counter);
        Console.WriteLine(line.SubString(line.IndexOf(userText),userText.Length));
        found++;
    }
}
Console.WriteLine("A total of {0} occurences found", found);

此处添加的行是

line.SubString(line.IndexOf(userText),userText.Length)

这意味着我们需要在SubString内找到line index ofuserText开始userText length,直到While ((line = myFile.ReadLine()) != null) { string linecmp = line.toUpper(); counter++; if (linecmp.Contains(userText.toUpper())) { Console.WriteLine("Found on line number: {0}", counter); Console.WriteLine(line.SubString(line.IndexOf(userText),userText.Length)); found++; } } Console.WriteLine("A total of {0} occurences found", found); 的长度

如果您只想比较字符串并显示原始字符串,则可以使用此代码

{{1}}

答案 2 :(得分:0)

我稍微修改了您的搜索功能,以解决之前遇到的问题。正如你在评论中提到的那样,你说它是'THEIR'和'THE'字样。

添加以下代码以解决不匹配问题。

string userText = Console.ReadLine() + " ";

修改下面的完整代码。

string line;
int counter = 0;

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

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

int found = 0;

while((line = myFile.ReadLine()) != null)
{
    line = line.ToUpper();
    counter++;
    if (line.Contains(userText.ToUpper()))
    {
        Console.WriteLine("Found on line number: {0}", counter);
        Console.WriteLine(line.Substring(line.IndexOf(userText)+1,userText.Length));
        found++;
    }
 }

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

希望这会对你有所帮助。