java 基礎 - 查找某個字串出現的次數及位置

查找某個字串出現的次數及位置get

public class search {
public static void main(String[] args){

String str = "abc123abcd1234";
String searchStr ="bc";
int count = getStrCount(str,searchStr);
System.out.println("count is: "+ count);

}


public static int getStrCount(String str,String searchStr){
int index =0;//define the index
int count =0;//define the count

while((index=str.indexOf(searchStr,index))!= -1) {

if (searchStr.equals(str.substring(index,index+searchStr.length()))) {

System.out.println("index is :" + index);//print index

index = index + searchStr.length();

count++;

}
}
return count;
}

}

 

運行結果:string

index is :1
index is :7
count is: 2class

相關文章
相關標籤/搜索