Java Program to Search Duplicate Words in the String

In this Program we are going to Search Duplicate Words in the Given String and Thus Display those words.

Lets Take Example: Welcome to Noteshacker Noteshacker name is good. here Duplicate word is “Noteshacker” and count is 3

For Finding Duplicate Words in a given String,First we have to Split String into Words and then check for duplicate words.

If count >1 then we got duplicate word print the given word along with its counter value.

Algorithm/Program Explanation

  1. Start
  2. Take String Input String s1.
  3. Split the String into words
  4. Define int count =1.
  5. Define and initialize Two For Loop
    • for(int i=0;i<split.length;i++)
    • for(int j=i+1;j<split.length;j++)
    • Check for Conditions
      • if(split[i].equals(split[j]))
      • count=count+1;
      • split[j]=” # “;//Replacing Repeated by #
    • Check for Conditions
      • if(split[i] !=”#”)
      • print( split[i]+ ” Count =” + count)
  6. End

Program

/*
Java Program To Count Duplicate Words */
import java.util.*;
public class count{


    public static void main(String args[]){
        String s1="Welcome to Noteshacker Noteshacker Noteshacker";//String Input
        String split[]=s1.split(" ");// Splitting String into Words
  int count=1;
  for(int i=0;i<split.length;i++){
      for(int j=i+1;j<split.length;j++){
          if(split[i].equals(split[j])){
              count=count+1;
              split[j]=" # ";//Replacing Repeated by #
          }
      }
      if(split[i] !="#"&& count>1)//printing only Duplicate words
{
          System.out.println( split[i]+ " Count =" + count);
 count=1;
      }
  }
    }
}
Output:
 Duplicate Words in String=Noteshacker =3
 Duplicate Words in String= #  =2// this of no use

Related Topics

Leave a Comment