Programming Examples

Java program to find the frequency of word present in string by using String Tokenizer


Write a Java program to find the frequency of word present in string by using  String Tokenizer Class.

Note . The word should not be a substring of a taken of the input string.

Sample Input:

The salesman is carrying a green bottle in the green bag and wearing a green cap. 

The frequency of the word to determine : green

sample output:

The frequency of the word green is : 3

Solution:

Output

Enter any String: 

The salesman is carrying a green bottle in the green bag and wearing a green cap

The frequency of the word to determine: 

green

The frequency of the word The salesman is carrying a green bottle in the green bag and wearing a green cap is :3

import java.util.*;
class FindFrequency
{
   
    public static void main(String arr[])
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter any String: ");
        String s=sc.nextLine();
        System.out.println("The frequency of the word to determine: ");
        String f=sc.nextLine();
        int count=0;
        StringTokenizer st=new StringTokenizer(s);
        String t="";
        while(st.hasMoreTokens())
        {
            t=st.nextToken();
            if(t.equals(f))
            {
                count++;
            }
        }       
        System.out.println("The frequency of the word "+s+" is :"+count);        
    }
}

Online Exam Quiz for One day Exam Online Typing Test CCC Online Test 2026 Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Best Website and Software Company in Allahabad