java 基础 - 查找某个字串出现的次数及位置
查找某个字串出现的次数及位置
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;
}
}
运行结果:
index is :1
index is :7
count is: 2