In: Computer Science
Write a method in java (with out using startwith,boolean true false) count that counts how many times a substring occurs in a string:For example: count("is", "Mississippi") will return 2. also add comment besides code.
//code screenshot
//code to copy
public class Count {
static int count(String substr,String mainstr)
{
int subLen = substr.length();
int mainLen= mainstr.length();
int count = 0;
/* A loop to slide substr one by one */
for (int i = 0; i <= mainLen - subLen; i++) {
/* For current index i, check for
pattern match */
int j;
for (j = 0; j < subLen; j++) {
if (mainstr.charAt(i + j) != substr.charAt(j)) {
break;
}
}
//if pattern substr match than inrease count by 1
if (j == subLen) {
count++;
j = 0;
}
}
return count; //return how many time string is repeted
}
public static void main(String[] args)
{
int countval=count("is", "Mississippi");
System.out.println("Count of substring in main String:"+countval);
}
}
//output screenshot