Repeated Word Count In A String Using C# Dictionary

In this blog, we are going to learn how to get a duplicate word in a given string. Today(4/11/2017) a person posted a query to find the duplicate word from a textbox and wanted to display it on another textbox. For this reason, I am posting this blog for all the users who needs to apply the same logic in the future. It will be helpful to others. 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace CountRepeatedWordCount  
  8. {  
  9.     class Program  
  10.     {  
  11.         static void Main(string[] args)  
  12.         {  
  13.             string Word;  
  14.             Console.WriteLine("Enter the word!..");  
  15.             Word = Console.ReadLine();   // Read the Input string from User at Run Time  
  16.             var Value = Word.Split(' ');  // Split the string using 'Space' and stored it an var variable  
  17.             Dictionary<stringint> RepeatedWordCount = new Dictionary<stringint>();  
  18.             for (int i = 0; i < Value.Length; i++) //loop the splited string  
  19.             {  
  20.                 if (RepeatedWordCount.ContainsKey(Value[i])) // Check if word already exist in dictionary update the count  
  21.                 {  
  22.                     int value = RepeatedWordCount[Value[i]];  
  23.                     RepeatedWordCount[Value[i]] = value + 1;  
  24.                 }  
  25.                 else  
  26.                 {  
  27.                     RepeatedWordCount.Add(Value[i], 1);  // if a string is repeated and not added in dictionary , here we are adding   
  28.                 }  
  29.             }  
  30.             Console.WriteLine();  
  31.             Console.WriteLine("------------------------------------");  
  32.             Console.WriteLine("Repeated words and counts");  
  33.             foreach (KeyValuePair<stringint> kvp in RepeatedWordCount)  
  34.             {  
  35.                 Console.WriteLine(kvp.Key + " Counts are " + kvp.Value);  // Print the Repeated word and its count  
  36.             }  
  37.             Console.ReadKey();  
  38.         }  
  39.     }  

Step 1

Copy the code and paste it on C# console Application.
 
Note

Create the Application with same name CountRepeatedWordCount or alter the copied code, as per your Application name.
 
Step 2

Save and Run the Application. Now, you can enter the string and see the output.
 


Feel free to add your comments. If you have any query regarding this, feel free to post.
X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now