[英]Most efficient way to count number of overlapping occurrences
如何有效地計算字符串中重疊出現的次數?
例如, count('XLXXXLXX','XX')
應該返回3
一種簡單的方法是使用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
}
這是對我來說最易讀的方式:
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;
}
嘗試這個。
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;
}
這段代碼有幫助嗎?
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);
}
我會推薦 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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.