Program to count the number of substring and word withing a given string
package assignment1;
/**
* @author snlkjha
*/
public class Pattern {
public static int substringCount(String pattern, String text) {
int M = pattern.length(),N = text.length(),count=0; // Variable decalartion
for(int i=0;i<=N-M;i++) {
int j=0;
while(j<M && text.charAt(i+j)==pattern.charAt(j)) j++;
if (j == M) {
count++;
i=i+M;
}
}
return count;
}
public static int wordCount(String pattern, String text) {
int M = pattern.length(),N=text.length(),count=0; // Variable declaration
for(int i = 0; i <= N - M; i++) {
int j=0;
while(j<M && text.charAt(i+j)==pattern.charAt(j)) j++;
if ((i-1==-1 ||text.charAt(i-1)==' ') && j == M && (i+M==N || (text.charAt(i+M)==' '||text.charAt(i+M)=='.'||text.charAt(i+M)==',') )) {
count++;
i=i+M;
}
}
return count;
}
public static void main(String[] args){
String x="a*b aabba*bbab a*b b a*b";
String y="a*b";
System.out.println("Number of substring "+y+" in '"+x+"':"+substringCount(y,x));
System.out.println("Number of word "+y+" in '"+x+"':"+wordCount(y,x));
}
}
/**
* @author snlkjha
*/
public class Pattern {
public static int substringCount(String pattern, String text) {
int M = pattern.length(),N = text.length(),count=0; // Variable decalartion
for(int i=0;i<=N-M;i++) {
int j=0;
while(j<M && text.charAt(i+j)==pattern.charAt(j)) j++;
if (j == M) {
count++;
i=i+M;
}
}
return count;
}
public static int wordCount(String pattern, String text) {
int M = pattern.length(),N=text.length(),count=0; // Variable declaration
for(int i = 0; i <= N - M; i++) {
int j=0;
while(j<M && text.charAt(i+j)==pattern.charAt(j)) j++;
if ((i-1==-1 ||text.charAt(i-1)==' ') && j == M && (i+M==N || (text.charAt(i+M)==' '||text.charAt(i+M)=='.'||text.charAt(i+M)==',') )) {
count++;
i=i+M;
}
}
return count;
}
public static void main(String[] args){
String x="a*b aabba*bbab a*b b a*b";
String y="a*b";
System.out.println("Number of substring "+y+" in '"+x+"':"+substringCount(y,x));
System.out.println("Number of word "+y+" in '"+x+"':"+wordCount(y,x));
}
}
Output :
Number of substring a*b in 'a*b aabba*bbab a*b b a*b' : 4
Number of word a*b in 'a*b aabba*bbab a*b b a*b' : 3