Write a java program to count how many times substring is present in Sentence :
import java.util.Scanner;
public class CountSubString {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Sentence ");
String str = sc.nextLine();
System.out.println("Enter Substring : ");
String substr=sc.nextLine();
int count=toCountSubstring(str,substr);
System.out.println("Entered Substring is present "+count+" times");
}
private static int toCountSubstring(String str, String substr) {
char []string =str.toCharArray();
char []subst=substr.toCharArray();
int count=0;
for(int i=0;i<string.length;i++) {
int j=0,k=i;
while(k<string.length && j<subst.length && (string[k]==subst[j])) {
k++;
j++;
}
if(j==subst.length) {
count++;
}
}
return count;
}
}
Comments
Post a Comment