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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3