如何有效地计算字符串中出现的重叠的数量?
例如,count('XLXXXLXX','XX')
应该返回3
发布于 2019-12-19 21:31:07
一种简单的方法是使用indexOf(String, int)
在源字符串中查找您要查找的模式的每一个匹配项。只需确保增加找到它的索引,这样就不会一直找到相同的索引。
用这种方法
public static int count(String source, String lookFor) {
int count = 0;
int i = -1;
while (i != 0) {
i = source.indexOf(lookFor, i) + 1;
if (i != 0) count++;
}
return count;
}
我在测试时得到了这个输出
public static void main(String[] args) {
System.out.println(count("XLXXXLXX", "XX")); // 3
System.out.println(count("XXX", "XX")); // 2
System.out.println(count("X", "XX")); // 0
}
发布于 2019-12-19 21:53:47
下面是我最容易读懂的方法:
public static int countOccurrences(String string, String sub) {
int count = 0;
int i = string.indexOf(sub);
while (i >= 0) {
++count;
i = string.indexOf(sub, i+1);
}
return count;
}
发布于 2019-12-19 21:36:09
尝尝这个。
public static int count(String s, String f) {
int count = 0;
int end = s.length() - f.length();
for (int i = 0; i <= end; ++i)
if (s.startsWith(f, i))
++count;
return count;
}
https://stackoverflow.com/questions/59416979
复制相似问题