统计子字符串在文本中出现次数,并打印出子串出现的位置索引
public static void main(String[] args) {
String parent = "你我他你呢什么时候你去黄山他";
String sub = "他";
System.out.println(countUseIndexOf(parent,sub));
System.out.println("--------------");
}
/**
* @description: 统计子串在文本中出现的次数
* @return:
* @author: Ming
*/
public static int countUseIndexOf(String text, String target) {
int count = 0;
int targetLength = target.length(),sentenceLength = text.length();
if (targetLength > sentenceLength) {
return count;
}
int index = text.indexOf(target);//第一次子串出现的位置,找不到返回-1
if(index != -1){
System.out.println("index="+index);
count++;
while (index >= 0) {
index = text.indexOf(target, index + targetLength);
if (index > 0){
System.out.println("index="+index);
count++;
}
}
}
return count;
}
简单并高效