我有一个
public static string[] words = {"word1","word2","word3"};
我想计算字符串中单词 1 的出现次数 + 单词 2 的出现次数 + 单词 3 的出现次数。
我试过了
Regex.Matches(string, "word1").Count
对于单个单词来说效果很好,但我不知道如何搜索所有字符串。 我不想使用 foreach 因为数组“words”最多可以包含 25 个字符串。 谢谢。
最佳答案
这是一种更通用的方法。
正则表达式让您可以更好地控制它找到的单词的上下文。
而且,我猜它要快得多,因为它一次性完成了所有事情
无需大量原语操作。
string[] words = { "word1", "word2", "word3" };
Regex rx = new Regex( @"(?is)(?:.*?\b(" + string.Join("|", words) + @")\b)+");
string strin = "There are some word3 and more words and word1 and more word3, again word1";
Match m = rx.Match( strin );
if ( m.Success )
Console.WriteLine("Found {0} words", m.Groups[1].Captures.Count);
输出
Found 4 words
上面的正则表达式使用单词边界 \b
.
替代边界选择:空白 (?<!\S) (?!\S)
关于c# - 计算文本中字符串数组中元素的总出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56299381/