Monday, 2 November 2015

Count Sub String Occurrence Algorithm With Example using JAVA

Count Sub String Occurrence Algorithm With Example using JAVA

Sub String Occurrence count means to check how many  times a particular  part of a string repeat in the given string.

Algorithm:

step 1: get the length of MainString and SubString variables and initialize i=j=count=0;
            ex:
            len1=mainString.length();
            len2=subString.length();

Step 2: start loop from i=0 to len1-len2;
            initialize the j with 0 and flag with true;

Step 3: check whether character of mainString at position i is equals to character of SubString at position j ?
             ex:
             if(mainString.charAt(i)==subString.charAt(j))

Step 4: if both are sem then start another loop with j=1 and j is j<=subString.length(); now check whether the character of mainString at position i+j is not Equals to character of SubString at position j. then make the flag = false and break the loop.
           ex:
           for(j=1;j<=SubString.length();j++){
                         if(mainString.charAt(i+j)!=subString(j)){
                                     flag=false;
                                       break;
                          }
            }

Step 5:out side the inner for loop check whether the flag value is true if yes then count= count+1
            ex:
            if(flag)
               count++;

Download Program: Click Here

Program:

import java.util.*;

public class reverse{
public static int getSubString(String mainString,String subString){
int max=1+mainString.length()-subString.length();
int count=0;
for(int i=0;i<max;i++){
boolean flag=true;
int j=0;
if(mainString.charAt(i)==subString.charAt(j)){
for(j=1;j<subString.length();j++){
if(mainString.charAt(i+j)!=subString.charAt(j)){
flag=false;
break;
}
}

}else
flag=false;
if(flag)
count++;
}
return count;
}
public static void main(String [] args){
Scanner input=new Scanner(System.in);
System.out.print("Enter Main String:");
String mainString=input.nextLine();
System.out.print("Enter Sub String :");
String subString=input.nextLine();

int count=getSubString(mainString,subString);

System.out.println("String Found:"+count);
}
}

compile the above code:javac subStringcounter.java
To Run the code: java subStringcounter

Output:


2 comments: