//方法一
public class StringTest {//"abkkcdkkefkkskk"
public static int getSubCount(String str,String key){
long startTime=System.currentTimeMillis();
int count=0;
int index=0;
while((index=str.indexOf(key))!=-1){
System.out.println(str);
str=str.substring(index+key.length());
count++;
}
long endTime=System.currentTimeMillis();
System.out.println("getSubCount="+(endTime-startTime));
return count;
}
//方法二(速度快)
public static int getSubCount_2(String str,String key){
long startTime=System.currentTimeMillis();
int count =0;
int index=0;
while((index=str.indexOf(key,index))!=-1){
System.out.println(index);
index=index+key.length();
count++;
}
long endTime=System.currentTimeMillis();
System.out.println("getSubCount_2="+(endTime-startTime));
return count;
}
public static void main(String[] args) {
String str="abkkcdkkefkkskk";
System.out.println(getSubCount(str,"kk"));
System.out.println("***********************************");
System.out.println(getSubCount_2(str,"kk"));
}
}