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

How to Efficiently Count Substring Occurrences in Java?

Linda Hamilton
Release: 2024-12-27 18:25:11
Original
527 people have browsed it

How to Efficiently Count Substring Occurrences in Java?

Finding Occurrence of a Substring Within a String: Troubleshooting and an Alternative Solution

When executing the provided Java code to count occurrences of a substring within a string, you may encounter issues with the algorithm not halting. This issue stems from the constant increment of lastIndex without placing a check to ensure it doesn't exceed the bounds of the string str.

To resolve this issue, modify the code to include a conditional check that verifies if lastIndex is still within the bounds of str:

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

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

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

    lastIndex += findStr.length();
}

System.out.println(count);
Copy after login

Alternatively, you can use the StringUtils.countMatches method from the Apache Commons Lang library:

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

System.out.println(StringUtils.countMatches(str, findStr));
Copy after login

This method simplifies the process of counting substring occurrences and ensures an efficient and reliable solution.

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