首頁 >Java >java教程 >如何高效統計字串中子字串的出現次數?

如何高效統計字串中子字串的出現次數?

Barbara Streisand
Barbara Streisand原創
2024-12-18 13:54:10885瀏覽

How to Efficiently Count Substring Occurrences in a String?

找出字串中出現的子字串

在下面的程式碼中,我們的目標是確定子字串findStr 在字符字串中出現的次數string str:

String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int lastIndex = 0;
int count = 0;

while (lastIndex != -1) {
    lastIndex = str.indexOf(findStr, lastIndex);

    if (lastIndex != -1)
        count++;

    lastIndex += findStr.length();
}

System.out.println(count);

但是,該演算法在某些情況下可能無法終止。問題在於,lastIndex = findStr.length() 可能會導致演算法搜尋超出字串末尾的位置。為了解決這個問題,我們可以使用以下方法:

String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int count = StringUtils.countMatches(str, findStr);
System.out.println(count);

此程式碼利用Apache Commons Lang 中的StringUtils.countMatches 方法,該方法為計算子字串出現次數提供了更強大、更有效率的解決方案。

以上是如何高效統計字串中子字串的出現次數?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn