Home >Java >javaTutorial >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!