獲取一個字符串在另一個字符串中出現的次數。
public static void main(String[] args) {
//方法一:
int count = 0 ;
int site ;
String s1 ="kpkpeekpkpeekp";
String s2 = "kp" ;
while ( ( site = s1.indexOf(s2) ) !=-1 ) {
s1 = s1.substring(site+s2.length()) ;
count ++ ;
}
System.out.println("出現"+count+"次");
//方法二:
String s = "ppdd dd ww ddsbddwsd dd";
int counts=0; int t = 0;
while(s.indexOf("dd",t)!=-1) {//從t的位置開始檢索
t=s.indexOf("dd",t)+1;
counts++;
}
System.out.println(counts);
}