Advertisement
sylviapsh

Word Count In Text

Jan 30th, 2013
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.09 KB | None | 0 0
  1. using System;
  2.  
  3. class WordCountInText
  4. {
  5.   //Write a program that reads a string from the console and lists all different words in the string along with information how many times each word is found.
  6.  
  7.   static void Main()
  8.   {
  9.     string text = "Write a program that reads a string from the console! It should list all different words in the string, along with information how many times each word is found.";
  10.     text = text.ToLower();
  11.  
  12.     char[] separators = { ' ', ',', '.', '!', '?', ':', ';', '/', '\\', };
  13.     string[] wordsArray = text.Split(separators,StringSplitOptions.RemoveEmptyEntries);
  14.  
  15.     Array.Sort(wordsArray);
  16.    
  17.     int counter = 1;
  18.     string currentWordToCount = wordsArray[0];
  19.     for (int i = 1; i < wordsArray.Length; i++)
  20.     {
  21.       if (wordsArray[i] == currentWordToCount)
  22.       {
  23.         counter++;
  24.       }
  25.       else
  26.       {
  27.         Console.WriteLine("{0,-15} : {1,3}", currentWordToCount, counter);
  28.         currentWordToCount = wordsArray[i];
  29.         counter = 1;
  30.       }
  31.     }
  32.     Console.WriteLine("{0,-15} : {1,3}", currentWordToCount, counter);
  33.   }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement