计算字符串中单词出现次数

时间:2015-02-09 17:17:45

标签: c# string count words

我在.Net C#中有这个项目,我必须计算字符串中出现的字数。我得到一个KeyNotFoundException,其中我正在递增变量以显示一个单词重复的次数。 代码如下:向下滚动以查找错误

public static Dictionary<string, int> Process(string phrase)
{
    Dictionary<string, int> wordsAndCount = new Dictionary<string, int>();

    string[] words = phrase.Replace("\"", "").Replace("'", "").Replace(".", "").Replace(",", "").Replace("\n", "").Split(' ');
    for (int index = 0; index <= words.Length; index++)
    {
        string word = words[index];
        wordsAndCount[word] = wordsAndCount[word] + 1;
    }
    Dictionary<string, int> dictionary = new Dictionary<string, int>();

    foreach (KeyValuePair<string, int> pair in wordsAndCount.OrderByDescending((s) => s.Key))
        dictionary.Add(pair.Key, pair.Value);

    wordsAndCount = dictionary;
    return wordsAndCount;
}

}

出现

错误

wordsAndCount[word] = wordsAndCount[word] + 1; KeyNotFoundException was unhandled
An unhandled exception of type 'System.Collections.Generic.KeyNotFoundException' occurred in mscorlib.dll

2 个答案:

答案 0 :(得分:1)

你的循环包含两个问题:

  • 如果密钥不存在,则无法使用密钥(使用ContainsKey进行测试)
  • 你应该循环直到索引&lt; words.Length

    for (int index = 0; index < words.Length; index++)
    {
        string word = words[index];
        if(!wordsAndCount.ContainsKey(word))
            wordsAndCount.Add(word, 1);
        else
            wordsAndCount[word]++;
    }
    

您还可以使用此方法对字典进行排序

var temp = wordsAndCount.OrderByDescending (ac => ac.Key);
return temp.ToDictionary (t => t.Key, t => t.Value);

答案 1 :(得分:0)

试试这个:

字符串A中字符串B的出现次数。

var NumberOfOccurrences = A.Split(new string[] { B }, StringSplitOptions.None).Length - 1;