检查字符串是否包含子字符串列表并保存匹配的字符串

acc*_*and 10 c# string contains

这是我的情况:我有一个表示文本的字符串

string myText = "Text to analyze for words, bar, foo";   
Run Code Online (Sandbox Code Playgroud)

以及要在其中搜索的单词列表

List<string> words = new List<string> {"foo", "bar", "xyz"};
Run Code Online (Sandbox Code Playgroud)

我想知道最有效的方法,如果存在,获取文本中包含的单词列表,类似于:

List<string> matches = myText.findWords(words)
Run Code Online (Sandbox Code Playgroud)

Hos*_*Rad 8

除了必须使用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
Run Code Online (Sandbox Code Playgroud)


Yuv*_*kov 5

您可以使用HashSet<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);
Run Code Online (Sandbox Code Playgroud)