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.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace CountRepeatedWordCount
- {
- class Program
- {
- static void Main(string[] args)
- {
- string Word;
- Console.WriteLine("Enter the word!..");
- Word = Console.ReadLine(); // Read the Input string from User at Run Time
- var Value = Word.Split(' '); // Split the string using 'Space' and stored it an var variable
- Dictionary<string, int> RepeatedWordCount = new Dictionary<string, int>();
- for (int i = 0; i < Value.Length; i++) //loop the splited string
- {
- if (RepeatedWordCount.ContainsKey(Value[i])) // Check if word already exist in dictionary update the count
- {
- int value = RepeatedWordCount[Value[i]];
- RepeatedWordCount[Value[i]] = value + 1;
- }
- else
- {
- RepeatedWordCount.Add(Value[i], 1); // if a string is repeated and not added in dictionary , here we are adding
- }
- }
- Console.WriteLine();
- Console.WriteLine("------------------------------------");
- Console.WriteLine("Repeated words and counts");
- foreach (KeyValuePair<string, int> kvp in RepeatedWordCount)
- {
- Console.WriteLine(kvp.Key + " Counts are " + kvp.Value); // Print the Repeated word and its count
- }
- Console.ReadKey();
- }
- }
- }
Step 1
Copy the code and paste it on C# console Application.
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.
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.
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.

Hakan GülPosted Apr 23, 2020, 4:32 PM
Can you convert this code to vb.net
shaik rahamtullaPosted Dec 5, 2018, 11:40 PM
Thanks, useful
Siva ChanduPosted Jan 27, 2018, 8:56 AM
Nice explanation super
Jyoti JodhaPosted Apr 12, 2017, 1:20 AM
Superb Sir, Thanks For Share