如何计算子字符串出现在 string 中的次数?到目前为止我有
static boolean doesAppear(String a, String b){
boolean appears;
appears = (b.indexOf(a) != -1) ? true : false;
return appears;
}
确认它确实出现了,但我不知道如何调整它以返回 true 计数 >= 2。
回答1
您可以使用 String#indexOf
的第二个参数 fromIndex
继续查找过去出现的 string。
public boolean doesAppear(String a, String b, int count){
int num = 0;
for(int idx = -1; num < count && (idx = b.indexOf(a, idx + 1)) != -1; num++);
// You may need to adjust idx + 1 to idx + a.length(),
// depending on whether or not you allow overlapping occurrences
return num >= count;
}