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

How to Efficiently Count Substring Occurrences in a String?

Barbara Streisand
Release: 2024-12-18 13:54:10
Original
818 people have browsed it

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);
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template