如何有效地计算字符串中重叠出现的次数?
例如,"unit":"1"
应该返回count('XLXXXLXX','XX')
答案 0 :(得分:1)
一种简单的方法是使用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
}
答案 1 :(得分:0)
尝试一下。
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;
}
答案 2 :(得分:0)
此代码有帮助吗?
public static void main(String[] args) {
String myString = "XLXXXLXX";
int fromIndex = -1;
int count = 0;
while (true) {
fromIndex = myString.indexOf("XX", fromIndex + 1);
if (fromIndex != -1) {
count++;
} else {
break;
}
}
System.out.println(count);
}
答案 3 :(得分:0)
这是我最容易理解的方式:
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;
}
答案 4 :(得分:0)
我建议使用String substring(<str>, index)
方法,因为它在眼睛上更容易。
如果您想尝试使用更基本的代码来了解幕后发生的事情,请使用字符数组方法。
private static int count(String givenStr, String overlappingStr) {
char[] first = givenStr.toCharArray();
char[] second = overlappingStr.toCharArray();
int matchCount = 0;
for (int i = 0; i < first.length; i++) {
int count = 0;
for (int j = 0, index = i; j < second.length && index < first.length; j++, index++) {
if (first[index] == second[j]) {
count++;
} else if (first[index] != second[j] && count > 0) {
break;
}
}
if (count == second.length) {
matchCount++;
}
}
return matchCount;
}