Advertisement
Guest User

Untitled

a guest
Jul 21st, 2017
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.58 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. /*
  6.  * Write a program that reads a string from the console and lists all
  7.  * different words in the string along with information how many times each word is found.
  8.  */
  9. namespace CounterDifferentWords
  10. {
  11.     class CounterDifferentWords
  12.     {
  13.         private static void PrintDifferentWordsAndCount(Dictionary<string, int> dictionary)
  14.         {
  15.             foreach (string str in dictionary.Keys)
  16.             {
  17.                 Console.WriteLine("{0} -> {1} times.", str, dictionary[str]);
  18.             }
  19.         }
  20.  
  21.         private static Dictionary<string, int> CountDifferentWordsInText(string[] words)
  22.         {
  23.             Dictionary<string, int> dictionary = new Dictionary<string, int>();
  24.             foreach (string str in words)
  25.             {
  26.                 if (!dictionary.ContainsKey(str))
  27.                 {
  28.                     dictionary.Add(str, 1);
  29.                 }
  30.                 else
  31.                 {
  32.                     dictionary[str]++;
  33.                 }
  34.             }
  35.             return dictionary;
  36.         }
  37.  
  38.         static void Main(string[] args)
  39.         {
  40.             string input = "Write a program that reads that string from the console the lists all";
  41.             Dictionary<string, int> dictionary = new Dictionary<string, int>();
  42.             input = input.ToLower();
  43.             string[] words = input.Split(' ', '.', ',');
  44.             dictionary = CountDifferentWordsInText(words);
  45.             PrintDifferentWordsAndCount(dictionary);
  46.         }
  47.     }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement