class MyCount{
public static int mycount(String s1, String s2){//统计s2在s1中出现的次数
int count=0,index;
while((index=s1.indexOf(s2))!=-1){
count++;
index+=s2.length();
if(index>s1.length()-1) break;//如果下一次搜索的起始位置超出当前s1长度,
//则跳出循环
s1=s1.substring(index);//从下一个位置起继续搜索
}
return count;
}
public static void main(String[] args){
String s1="abcdebcfbcbc",s2="bc";
System.out.println("s1="+s1);
System.out.println("s2="+s2);
System.out.println("s2在s1中出现"+mycount(s1,s2)+"次");
}
} |
|