"abchelloabchello"中计算子串"abc"出现的次数。
public class Test {
public static void main(String[] args) {
String str = "helloabchello";
String s = "abc";
System.out.println("-------------------");
int count = count1(str,s);
System.out.println(count);
System.out.println("-------------------");
int c2 = count2(str,s);
System.out.println(c2);
System.out.println("-----------");
System.out.println(count3(str,s));
}
public static int count3(String str , String s){
String newStr = str.replace(s,"");
return (str.length()-newStr.length())/s.length();
}
public static int count2(String str,String s){
int count = 0;
String temp = str;
int index ;
while((index = temp.indexOf(s))!=-1){
temp = temp.substring(index+s.length());
count++;
}
return count;
}
public static int count1(String str,String s){
int count = 0;
int index = str.indexOf(s);
while (index!=-1){
index = str.indexOf(s,index+s.length());
count++;
}
return count;
}
}