我有3个文本文件,即
input.txt
array1.txt
array2.txt
input.txt 文件包含如下行:
the file in
the computer is
removedby user,
there are seven
wonders in the world
ithink...
array1.txt 文件包括:
computer
user
good
array2.txt 文件包括:
seven
world
none
我想用 array1.txt 和 array2.txt 检查 input.txt 中是否存在单词
我想说的是,例如:input.txt 中的单词与 array1.txt 中的单词匹配意味着输出必须是“computer”存在于 array1 中。如果单词与 array2.txt 匹配意味着它应该显示 array2 中存在的单词。
输出:words computer 和 user 出现在 array1 words world 中,七个出现在 array2 中
我的 C# 代码:
int count;
using (StreamReader reader = File.OpenText("C:/Users/input.txt"))
{
string contents = reader.ReadToEnd();
MatchCollection matches = Regex.Matches(contents, "computer", RegexOptions.IgnoreCase);
count = matches.Count;
}
if (count > 0)
{
MessageBox.Show("present");
}
else
{
MessageBox.Show("absent");
}
最佳答案
我会采用不同的方法:
- 要读取文件(除非它是一个需要流式处理的非常大的文件),我会使用
File.ReadAllText
或File.ReadAllLines
。 - 为了检查文本中是否存在数组中的字符串,我会使用
Contains
而不是正则表达式。 - 最后我会使用 linq
Where
检查数组中每一项的谓词的方法
所以:
var arr1 = File.ReadAllLines("array1.txt"); // Reading to get string[] - item for each line
var arr2 = File.ReadAllLines("array2.txt");
var input = File.ReadAllText("input.txt"); // Reading to get one string for all text
var arr1WordsInInput = arr1.Where(input.Contains);
var arr2WordsInInput = arr2.Where(input.Contains);
如果你想找到匹配项的所有索引,你可以使用这个问题的答案中建议的函数 Finding ALL positions of a substring in a large string in C#像这样:
var result = arr1.Select(w => new { Word = w, Indexes = input.AllIndexesOf(w) })
.Where(w => w.Indexes.Any());
这将返回一个 IEnumerable
,其中每个项目包含两个属性:匹配词和在 input
文本中找到它的索引
关于c# - c# - 如何搜索文本文件中存在的两个或多个单词的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46272148/