Home >Java >javaTutorial >How Can I Reliably Count Substring Occurrences in a String?

How Can I Reliably Count Substring Occurrences in a String?

DDD
DDDOriginal
2024-12-14 06:27:10957browse

How Can I Reliably Count Substring Occurrences in a String?

Count Substring Occurrences in a String

When attempting to ascertain the occurrences of a substring within a string, a common issue arises when the search algorithm fails to terminate. To rectify this, it is imperative to address the following:

Understanding the Issue

Consider the example provided, where the goal is to count occurrences of "hello" in the string "helloslkhellodjladfjhello." The algorithm iteratively searches for the substring using the indexOf method. However, it incrementally adjusts the lastIndex by the length of the substring, resulting in an infinite loop.

A Reliable Solution

To overcome this, one can employ the countMatches method from Apache Commons Lang. This predefined function accurately counts substring occurrences, as demonstrated in the code below:

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

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

This yields the expected count of 3.

The above is the detailed content of How Can I Reliably 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