For example: javascriptjavasejavaeejavame
Ideas:
Define a counter
Get the location where Java first appears
Continue to get the location where Java appears from the remaining string after the first occurrence position, count every time it is obtained
When the acquisition is not available, the counting is completed
The code copy is as follows:
class StringCount{
public static void main(String[] args){
String s = "javascriptjavasejavaeejavame";
int count = getSubString(s,"java");
System.out.println(count);
}
public static int getSubString(String str,String key){
int count = 0;
int index = 0;
while((index=str.indexOf(key,index))!=-1){
index = index+key.length();
count++;
}
return count;
}
}
The second method:
The code copy is as follows:
public static int getSubCount_2(String str,String key){
int count = 0;
int index = 0;
while ((index=str.indexOf(key,index))!=-1){
str = str.subtring(index+key.length());
count++;
}
return count;
}