Find Duplicate or Repeating Words in String Using C#

main.cs

 using System;  
                      
public class DuplicateWord  
{  
    public static void Main()  
    {  
        String string1 = "Small brown bug bit a small brown dog on his small brown nose";  
        int count;  
          
        //Converts the string into lowercase  
        string1 = string1.ToLower();  
          
        //Split the string into words using built-in function  
        String[] words = string1.Split(' ');  
          
        Console.WriteLine("Duplicate words in a given string : ");  
        for(int i = 0; i < words.Length; i++) {  
            count = 1;  
            for(int j = i+1; j < words.Length; j++) {  
                if(words[i].Equals(words[j])) {  
                    count++;  
                    //Set words[j] to 0 to avoid printing visited word  
                    words[j] = "0";  
                }  
            }  
              
            //Displays the duplicate word if count is greater than 1  
            if(count > 1 && words[i] != "0")  
                Console.WriteLine(words[i]);  
        }  
    }  
}

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.