在文本文件中搜索多个单词

Search multiple words in a text file

我做了一个代码在一个文本文件中搜索几个词,但只搜索到最后一个词,我想解决这个问题 代码:

string txt_text;
string[] words = {
  "var",
  "bob",
  "for",
  "example"
};
StreamReader file = new StreamReader("test.txt");
foreach(string _words in words) {
  while ((txt_text = file.ReadToEnd()) != null) {
    if (txt_text.Contains(_words)) {
      textBox1.Text = "founded";
      break;
    } else {
      textBox1.Text = "nothing founded";
      break;
    }
  }
}

我会将文本保存在一个变量中,然后遍历您的单词以检查它是否存在于文件中。像这样:

string[] words = { "var", "bob", "for", "example"};
var text = file.ReadToEnd();

List<string> foundWords = new List<string>();

foreach (var word in words)
{
    if (text.Contains(word))
        foundWords.Add(word);
}

然后,列表 foundWords 包含所有匹配的词。

(PS:不要忘记将您的 StreamReader 放在 using 语句中,以便正确处理它)

首先,您可以在 Linq 的帮助下摆脱 StreamReader 和循环并 查询 文件

using System.Linq;
using System.IO;

...

textBox1.Text = File
  .ReadLines("test.txt")
  .Any(line => words.Any(word => line.Contains(word))) 
     ? "found"
     : "nothing found";

如果你坚持循环,你应该放弃 else:

 // using - do not forget to Dispose IDisposable
 using StreamReader file = new StreamReader("test.txt");

 // shorter version is
 // string txt_text = File.ReadAllText("test.txt");
 string txt_text = file.ReadToEnd();

 bool found = false;

 foreach (string word in words) 
   if (txt_text.Contains(word)) {
     // If any word has been found, stop further searching
     found = true;

     break; 
   } // no else here: keep on looping for other words

 textBox1.Text = found
   ? "found"
   : "nothing found";