This is the first solution to identify the duplicate words in a given input sentence of strings, using the core logic.
import java.util.Scanner;
public class Duplicatewords {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner inpStr=new Scanner(System.in);
System.out.println("Enter any sample sentence");
String sentence=inpStr.nextLine();
String [] words=sentence.split(" ");
String repWords = "";
//Traversing through the split words array using nested for loop and comparing each word with remaining words
for(int i=0;i<words.length;i++) {
for(int j=i+1;j<words.length;j++) {
if(words[i].contentEquals(words[j])) {
//Maintaining the repeated words string to avoid displaying the message every time when same word encounters
if (!repWords.contains(words[i])) {
repWords=repWords.concat(words[i]).concat(" ");
System.out.println("The word="+words[i]+" is repeated");
continue;
}
}
}
}
inpStr.close();
}
}
Enter any sample sentence
This example demonstrates that This example, This example repeated
The word=This is repeated
The word=example is repeated

Leave a comment