Search code examples
c#stringcountwords

Count number of word occurrences in a string


I have this project in .Net C#, where I have to count the number of word occurances in a string. I get a KeyNotFoundException where at a point where I am incrementing the variable to show how many times a word is repeated. The code is as follows: scroll down for the error

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;
}

}

error at

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

Solution

  • Your loop contains two problems:

    • You can't use a key if it doesn't exist (Test with ContainsKey)
    • You should loop until index < 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]++;
      }
      

    You could also trim away a bit of code using this approach to sort your dictionary

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