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

How to Correctly Count Substring Occurrences in a Java String?

DDD
DDDOriginal
2025-01-04 15:25:40518browse

How to Correctly Count Substring Occurrences in a Java String?

How to Find the Number of Occurrences of a Substring in a String

Many developers encounter issues when attempting to determine the frequency of a substring's occurrence within a given string. One such case involves the following algorithm:

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);

Why does the algorithm fail?

Despite successfully identifying the first occurrence of "hello" at index 0, the algorithm enters an endless loop when searching for subsequent occurrences. This is because after the first occurrence is found, lastIndex findStr.length() becomes equal to 5, but the next "-1" result returned by indexOf() causes the while loop to iterate again with lastIndex still set to 0.

How to resolve the issue?

There are several ways to resolve this issue. One is to utilize a different substring searching method, such as Apache Commons Lang's StringUtils.countMatches(). Here is an example:

String str = "helloslkhellodjladfjhello";
String findStr = "hello";

System.out.println(StringUtils.countMatches(str, findStr)); // Outputs 3

Alternatively, you can modify the original algorithm to handle the "-1" case:

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();
    } else {
        break; // Exit the loop if no more occurrences are found
    }
}

System.out.println(count); // Outputs 3

The above is the detailed content of How to Correctly Count Substring Occurrences in a Java 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