Java program to count number of duplicate words in given string


Program

//Program to count repeated words in string
public class CountWords
{

public static void main(String[] args)
{
String input="Welcome to Java Session Session Session"; //Input String
String[] words=input.split(" "); //Split the word from String
int wrc=1; //Variable for getting Repeated word count

for(int i=0;i<words.length;i++) //Outer loop for Comparison
{
for(int j=i+1;j<words.length;j++) //Inner loop for Comparison
{

if(words[i].equals(words[j])) //Checking for both strings are equal
{
wrc=wrc+1; //if equal increment the count
words[j]="0"; //Replace repeated words by zero
}
}
if(words[i]!="0")
System.out.println(words[i]+"--"+wrc); //Printing the word along with count
wrc=1;

}

}

}

Output

Welcome--1

to--1

Java--1

Session--3



Related Post

Comments

Sanjana
         Can you please explain why we have set wrc=1; at the end
San
         if we put "Session to Java Session Session Welcome" an extra "--1" will be printed plz check with that
Deba
         Hi my name is Deba Hi my father is PK Output is Hi 2 my 2 name 1 is 2 Deba 1 father 4 PK 1 father is returning 4 which is absolutely wrong. I have coded in same way. Its only works fine when repeated words are consecutive. Code: public void wrdCnt(String input1) { input1 = input1.replace(".", ""); System.out.println(input1); String []tmp = input1.split(" "); int count = 1; for (int i = 0; i < tmp.length; i++) { for (int j = i+1; j < tmp.length; j++) { if(tmp[i].equals(tmp[j])) { count = count+1; tmp[j]="0"; System.out.println(tmp[j]+" -- "+count); } } if(tmp[i]!="0") { System.out.println(tmp[i]+" "+count); count=1; } } }

©candidjava.com