-2

我编写了一个代码来搜索文本文件中的几个单词,但只搜索最后一个单词,我想解决它的代码:

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;
    }
  }
}
4

2 回答 2

1

首先,你可以在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";
于 2021-08-29T18:44:45.023 回答
0

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

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声明中,以便正确处理)

于 2021-08-29T18:39:44.373 回答