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

How Can I Reliably Count Substring Occurrences in a String?

DDD
Release: 2024-12-14 06:27:10
Original
957 people have browsed it

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template