Home >Java >javaTutorial >How to Efficiently Count Substring Occurrences in a String?
Finding Substring Occurrences in a String
In the following code, our goal is to determine the number of times the substring findStr appears within the string str:
String str = "helloslkhellodjladfjhello"; String findStr = "hello"; int lastIndex = 0; int count = 0; while (lastIndex != -1) { lastIndex = str.indexOf(findStr, lastIndex); if (lastIndex != -1) count++; lastIndex += findStr.length(); } System.out.println(count);
However, this algorithm may fail to terminate under certain circumstances. The issue lies in the fact that lastIndex = findStr.length() might cause the algorithm to search beyond the end of the string. To resolve this, we can instead use the following approach:
String str = "helloslkhellodjladfjhello"; String findStr = "hello"; int count = StringUtils.countMatches(str, findStr); System.out.println(count);
This code utilizes the StringUtils.countMatches method from Apache Commons Lang, which provides a more robust and efficient solution for counting substring occurrences.
The above is the detailed content of How to Efficiently Count Substring Occurrences in a String?. For more information, please follow other related articles on the PHP Chinese website!