Java string comparison gets an example of the number of occurrences of a string
- 2020-04-01 02:44:51
- OfStack
For example: javascriptjavasejavaeejavame
Ideas:
Define a counter
Gets the location where Java first appeared
From the remaining string after the first occurrence of the location of the Java occurrence continues to be counted each time the location is obtained
When the fetch is unavailable, the count completes
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 way:
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;
}