Frequency of Repeated words in a string in Java

In this Java tutorial, we are going to find the frequency of the repeated words in Java. In order to do this, we have taken a sentence and split it into strings and compare each string with succeeding strings to find the frequency of the current string. Thus we can count the occurrences of a word in a string in Java.

How to count repeated words in a string in java

Before jumping into the code snippet to count repeated words in a string in java take a look at these below things.

What is split() string in Java?

split() is used to split a string into substrings based on regular expression. Suppose, you have a sentence and you have to deal with each string(words) of the sentence then there we use split()



The algorithm to find the frequency of Repeated word in a sentence in Java

  1. First, we have entered a string and then using split() string method. We split the input string into substrings based on regular expression.
  2. Using for loop we start checking from the first substring and check for strings those are equal to current string and incrementing the count.
  3. We initialize the count from 1 because we have to include the current string along with succeeding repeating string.
  4. We are printing those strings for which we are getting count more than one and the current string along with repeating string “-1”. So we will not count that string again.

Java Code to count repeated words in a string in java

import java. util. Scanner;

public class codespeedy
{
    public static void main(String[] args)
    {
        Scanner scan= new Scanner(System.in);
        String str=scan.nextLine();
        
        String[] s=str.split(" ");	
        
        int count=1;
        
        for(int i=0;i<=s.length;i++)
        {
            for(int j=i+1;j<s.length;j++)
            {
              if(s[i].equals(s[j]) && s[i]!="-1")
                {
                     s[j]="-1";
                    count++; 
                }
            }
            
    
            if(count>1 && s[i]!="-1")
            {
                System.out.println(s[i]+" "+count);
                 s[i]="-1";
            }
            count=1;
        }
    }
}

INPUT

I am indian , I am proud to be indian .

OUTPUT

I 2
am 2
indian 2

So, as we see in input sentence I is repeating 2 times. am is repeating 2 times and Indian is repeating 2 times. So these repeating strings or we can say substrings of input string along with their frequency are our outputs.

One response to “Frequency of Repeated words in a string in Java”

  1. Radhika Singh says:

    Nice explained Sir

Leave a Reply

Your email address will not be published. Required fields are marked *