使用c#中的字典计算字符串中每个重复单词的出现次数

编辑:我详细阐述了我的问题更多..解决方案在这里是一个修复重复的单词..我被问到每个重复的单词

我是新手……可能不是一个好问题。 ……

这是字符串

string str = "this this is is aa string" 

在采访中,我被要求将每个重复关键字的计数存储在通用字典中,然后按顺序显示它们

例如,“is”关键字的出现次数为2

类似的链接
: 在字符串C#中找到最多出现的字符? 这是关于寻找角色

查找文本中单词出现的列表单词,这是在python中

在javaScript中删除字符串中重复单词的出现

如何使用string.match方法查找字符串中同一个单词的多个匹配项? 不相关

..请建议

LINQ非常简单:

 string str = "this is is a string"; string[] words = str.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries); 

(你也可以像@markieo一样使用Regex.Split(str, @"\W+")作为答案。区别在于它还会检测被引号和其他标点符号包围的单词。感谢@JonB指出这方面在评论中。)

 Dictionary statistics = words .GroupBy(word => word) .ToDictionary( kvp => kvp.Key, // the word itself is the key kvp => kvp.Count()); // number of occurences is the value int isCount = statistics["is"]; // returns 2 

编辑:

我正在发布满足您增强要求的代码。 但是对于未来,只需发布​​另一个问题,而不是修改已经回答的问题!

 // retrieving all duplicate words string[] duplicates = statistics .Where(kvp => kvp.Value > 1) .Select(kvp => kvp.Key) .ToArray(); // counting all duplicates and formatting it into a list in the desired output format string output = String.Join( "\n", statistics .Where(kvp => kvp.Value > 1) .Select(kvp => String.Format( "count(\"{0}\") = {1}", kvp.Key, kvp.Value)) .ToArray() // this line is only needed on older versions of .NET framework ); 

试试以上内容:

  string str = "this this is is aa string"; private int count(string key) { string[] ar = str.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries); Dictionary d = new Dictionary(); for (int i = 0; i < ar.Length; i++) d.Add(i, ar[i]); return d.Where(x => x.Value == key).ToList().Count; } 

函数调用:

 count(str, "is"); 

您可以使用此代码获取字符串中所有单词的数组。

 static string[] SplitWords(string s) { return Regex.Split(s, @"\W+"); } 

然后你可以使用foreach循环来计算单词在数组中出现的所有时间。 像这样:

 int count = 0; foreach(string s in SplitWords("This is is a string"){ if(s == "is"){ count++; } } 

int count是单词在字符串中出现的次数。

资料来源: http : //www.dotnetperls.com/split