Home >>Java Programs >Java program to find the duplicate words in a string
In this example, we will create a java program to find out the duplicate words present in the string and display those words.
public class Main
{
public static void main(String[] args)
{
String string = "Peter Piper picked a peck of pickled peppers.
A peck of pickled peppers Peter Piper picked If Peter Piper picked a peck of pickled peppers Where’s the peck of pickled peppers Peter Piper picked?";
int count;
string = string.toLowerCase();
String words[] = string.split(" ");
System.out.println("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++;
words[j] = "0";
}
}
if(count > 1 && words[i] != "0")
System.out.println(words[i]);
}
}
}