统计字符串中单词出现的次数

Count number of word occurrences in a string

我在 .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

您的循环包含两个问题:

  • 如果密钥不存在则不能使用(使用 ContainsKey 测试)
  • 你应该循环直到索引 < 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]++;
    }
    

您还可以 trim 使用这种方法对您的字典进行排序,减少一些代码

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

试试这个:

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

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