Sunday, August 11, 2019

Java Program to Count repeated words in String

This tutorial explains how to count word in string in java application. Lets see the Following Java program to counts how many times a word appears in a String or find repeated words. It can help you in to find the most frequent words in a string also check the count which will be equal to one for unique words.

Java Program to Count repeated words in String
CountWords.java 
package demo;

import java.io.IOException;

public class CountWords  {

 public static void main(String[] args) throws IOException {
  // TODO Auto-generated method stub

    String input="Simple Form Validation In Reactjs Example Reactjs";  //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:-
-----------------

This is all about Java Program to Count repeated words in String. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.

No comments:

Post a Comment