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. namespace CountRepeatedWordCount
  7. {
  8. class Program
  9. {
  10. static void Main(string[] args)
  11. {
  12. string Word;
  13. Console.WriteLine("Enter the word!..");
  14. Word = Console.ReadLine(); // Read the Input string from User at Run Time
  15. var Value = Word.Split(' '); // Split the string using 'Space' and stored it an var variable
  16. Dictionary<string, int> RepeatedWordCount = new Dictionary<string, int>();
  17. for (int i = 0; i < Value.Length; i++) //loop the splited string
  18. {
  19. if (RepeatedWordCount.ContainsKey(Value[i])) // Check if word already exist in dictionary update the count
  20. {
  21. int value = RepeatedWordCount[Value[i]];
  22. RepeatedWordCount[Value[i]] = value + 1;
  23. }
  24. else
  25. {
  26. RepeatedWordCount.Add(Value[i], 1); // if a string is repeated and not added in dictionary , here we are adding
  27. }
  28. }
  29. Console.WriteLine();
  30. Console.WriteLine("------------------------------------");
  31. Console.WriteLine("Repeated words and counts");
  32. foreach (KeyValuePair<string, int> kvp in RepeatedWordCount)
  33. {
  34. Console.WriteLine(kvp.Key + " Counts are " + kvp.Value); // Print the Repeated word and its count
  35. }
  36. Console.ReadKey();
  37. }
  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.