Home >Java >javaTutorial >How to Efficiently Count Substring Occurrences in a String?

How to Efficiently Count Substring Occurrences in a String?

Barbara Streisand
Barbara StreisandOriginal
2024-12-18 13:54:10816browse

How to Efficiently Count Substring Occurrences in a String?

Finding Substring Occurrences in a String

In the following code, our goal is to determine the number of times the substring findStr appears within the 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);

However, this algorithm may fail to terminate under certain circumstances. The issue lies in the fact that lastIndex = findStr.length() might cause the algorithm to search beyond the end of the string. To resolve this, we can instead use the following approach:

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

This code utilizes the StringUtils.countMatches method from Apache Commons Lang, which provides a more robust and efficient solution for counting substring occurrences.

The above is the detailed content of How to Efficiently Count Substring Occurrences in a String?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn