Count the number of occurrences of each word in a string and stores them in a generic sorted dictionary. - CSharp Collection

CSharp examples for Collection:SortedDictionary

Description

Count the number of occurrences of each word in a string and stores them in a generic sorted dictionary.

Demo Code

using System;/*from  ww w  .  j av a2s  .  c o  m*/
using System.Text.RegularExpressions;
using System.Collections.Generic;
class MainClass
{
   static void Main()
   {
      SortedDictionary<string, int> dictionary = CollectWords();
      DisplayDictionary(dictionary); // display sorted dictionary content
   }
   private static SortedDictionary<string, int> CollectWords()
   {
      var dictionary = new SortedDictionary<string, int>();
      string input = "this is a test test this is a test";
      // split input text into tokens
      string[] words = Regex.Split(input, @"\s+");
      // processing input words
      foreach (var word in words)
      {
         var key = word.ToLower(); // get word in lowercase
         if (dictionary.ContainsKey(key))
         {
            ++dictionary[key];
         }
         else
         {
            // add new word with a count of 1 to the dictionary
            dictionary.Add(key, 1);
         }
      }
      return dictionary;
   }
   private static void DisplayDictionary<K, V>(SortedDictionary<K, V> dictionary)
   {
      Console.WriteLine($"\nSorted dictionary contains:\n{"Key",-12}{"Value",-12}");
      foreach (var key in dictionary.Keys)
      {
         Console.WriteLine($"{key,-12}{dictionary[key],-12}");
      }
      Console.WriteLine($"\nsize: {dictionary.Count}");
   }
}

Result


Related Tutorials