在文本文件中搜索多个单词 [英] Search multiple words in a text file

查看:66
本文介绍了在文本文件中搜索多个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I made a code to search for several words in a text file but only the last word is searched, I would like to solve it code:

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

推荐答案

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

First of all, you can get rid of StreamReader and loop and query the file with a help of Linq

using System.Linq;
using System.IO;

...

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

如果你坚持循环,你应该去掉else:

If you insist on loop, you should drop 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";

这篇关于在文本文件中搜索多个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆