计算文本中字符串数组中元素的总出现次数

时间:2019-05-24 20:48:06

标签: c# arrays regex count find-occurrences

我有一个

public static string[] words = {"word1","word2","word3"};

我想计算字符串中word1的出现+ word2的出现+ word3的出现。

我尝试了

Regex.Matches(string, "word1").Count 

这对于一个单词来说很好用,但是我不知道如何搜索所有字符串。 我不想使用foreach,因为数组“ words”最多可以包含25个字符串。 谢谢。

3 个答案:

答案 0 :(得分:3)

这是一种更通用的方法。
正则表达式使您可以更好地控制所找到单词的上下文。
而且,我猜它要快得多,因为它可以一次完成所有操作
无需大量原始操作。

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)

答案 1 :(得分:1)

您可以使用System.Linq来获取所有Sum的{​​{1}}中的Count,方法是:

Matches

答案 2 :(得分:0)

您最好的(也许只有)选项是一个循环遍历单词列表的循环。

我的偏好是这样的:

int intTotalWordCount=0;

for (int intJ=0;intJ<words.Length;intJ++)
{
    intTotalWordCount+=Regex.Matches(string, words[intJ]).Count;
}

Console.WriteLine (@"Final word count = {0}",intTotalWordCount;

当然,您也可以将上述块包装在以intTotalWordCount作为其返回值的方法中。