Java program to find the frequency of one string in another string.



import java.util.Scanner;
public class WordFrequencyCounter {
    public static void main(String args[]) {
        Scanner scan = new Scanner(System.in);
        System.out.println("enter main string");
        String s = scan.nextLine();
        System.out.println("enter string to be searched");
        String f = scan.nextLine();
        s = s + " ";
        int l = s.length();
        char a;
        int c = 0;
        String s1 = "";
        for (int i = 0; i < l; i++) {
            a = s.charAt(i);
            if (a != ' ') {
                s1 = s1 + a;
            } else {
                if (s1.equalsIgnoreCase(f) == true) {
                    c++;
                }
                s1 = "";
            }
        }
        System.out.println("Frequency of the word " + f + " is " + c);
    }                                         
}

Output:
Enter main string
Umesh Kumar Kushwaha Kumar
enter string to be searched
Kumar
Frequency of the word Kumar is 2



1 comment:

  1. String string="Umesh Kumar Kushwaha Kumar ";
    String arr[]=string.split(" ");
    int count=0;
    String search="kumar";
    for (int i = 0; i < arr.length; i++) {
    if(search.equals(arr[i]) )
    count++;
    }
    System.out.println("Counter is = "+count);

    ReplyDelete