Saturday, 18 June 2016

Program to find the frequency of a SubString in a given String.

Explanation :
If String ="For each rose,a rose is a rose" and SubString ="rose" then,
output will be "rose has occured 3 times".

Code:

import java.util.Scanner;
import java.util.StringTokenizer;
public class SubStringCount
{
      public static void main(String args[])
     {
         int count=0;
         Scanner sc = new Scanner(System.in);
         System.out.println("Enter any String");
         String x=sc.nextLine();
         System.out.println("Enter Sub String");
         String y=sc.nextLine();
         StringTokenizer st=new StringTokenizer(x,", ");
        while(st.hasMoreTokens())
       {
             String st1 = (String) st.nextToken();
               if(st1.equals(y))
              {
                   count ++;
               }
        }
             System.out.println(y+" has occured "+ count+ " times in "+x);
             sc.close();
}
}

No comments:

Post a Comment