我的情况是:我有一个代表文本的字符串。
string myText = "Text to analyze for words, bar, foo";
还有一个要在其中搜索的单词列表
List<string> words = new List<string> {"foo", "bar", "xyz"};
如果有的话,我想知道获取文本中包含的单词列表最有效的方法,就像这样:
List<string> matches = myText.findWords(words)
这个查询没有特别的分析,除了你需要使用Contains
方法。所以你可以尝试这样做:
string myText = "Text to analyze for words, bar, foo";
List<string> words = new List<string> { "foo", "bar", "xyz" };
var result = words.Where(i => myText.Contains(i)).ToList();
//result: bar, foo
\b
可以帮助解决该问题。 - BasHashSet<string>
并交集两个集合:string myText = "Text to analyze for words, bar, foo";
string[] splitWords = myText.Split(' ', ',');
HashSet<string> hashWords = new HashSet<string>(splitWords,
StringComparer.OrdinalIgnoreCase);
HashSet<string> words = new HashSet<string>(new[] { "foo", "bar" },
StringComparer.OrdinalIgnoreCase);
hashWords.IntersectWith(words);
HashSet
的示例,OP 可以在任何分隔符上拆分。他还可以在将字符串插入集合之前修剪它们,但我没有这样做。 - Yuval Itzchakov一个正则表达式的解决方案
var words = new string[]{"Lucy", "play", "soccer"};
var text = "Lucy loves going to the field and play soccer with her friend";
var match = new Regex(String.Join("|",words)).Match(text);
var result = new List<string>();
while (match.Success) {
result.Add(match.Value);
match = match.NextMatch();
}
//Result ["Lucy", "play", "soccer"]
如果你想使用myText.findWords(words)
,你可以创建一个扩展方法来实现这个功能,它可以作为String类的一个扩展。
public static class StringExtentions
{
public static List<string> findWords(this string str, List<string> words)
{
return words.Where(str.Contains).ToList();
}
}
使用方法:
string myText = "Text to analyze for words, bar, foo";
List<string> words = new List<string> { "foo", "bar", "xyz" };
List<string> matches = myText.findWords(words);
Console.WriteLine(String.Join(", ", matches.ToArray()));
Console.ReadLine();
结果:
foo,bar
这是一个简单的解决方案,考虑了空格和标点符号:
static void Main(string[] args)
{
string sentence = "Text to analyze for words, bar, foo";
var words = Regex.Split(sentence, @"\W+");
var searchWords = new List<string> { "foo", "bar", "xyz" };
var foundWords = words.Intersect(searchWords);
foreach (var item in foundWords)
{
Console.WriteLine(item);
}
Console.ReadLine();
}
myText
的大小是多少,你将进行多少次搜索操作? - npintiContains
方法可以匹配,而使用Split
方法则不能。 - juharr