2015-11-30 152 views
1

我正在研究一个用于搜索输入文本文件(我选择的)的小代码。我正在创建一个搜索功能。到目前为止,我得到它显示搜索词在文本文件中出现多少次以及行号。我需要一些帮助来显示搜索到的单词在文本文件中的显示方式。例如,如果我搜索单词“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); 

回答

1

可以使用的IndexOf,而不是包含因为你想不区分大小写的搜索:

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

非常好!这也会有所帮助。 – Bake

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) 

这意味着我们需要找到一个SubStringline内从index of开始的userText首次出现和钱柜的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); 
+0

这个工程!现在,我需要整合不区分大小写。谢谢。 – Bake

+0

在两侧添加'toUpper()'使其不区分大小写。 –

+0

我遇到了问题。假设我搜索单词“the”,它也在单词“their”中找到它。我如何绕过这个问题? – Bake

0

我稍微修改了您的搜索功能来解决您之前遇到的问题。正如你在评论中提到的那样,你说它与'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(); 

希望这可以帮助你。