Finding Occurrence of a Substring Within a String: Troubleshooting and an Alternative Solution
When executing the provided Java code to count occurrences of a substring within a string, you may encounter issues with the algorithm not halting. This issue stems from the constant increment of lastIndex without placing a check to ensure it doesn't exceed the bounds of the string str.
To resolve this issue, modify the code to include a conditional check that verifies if lastIndex is still within the bounds of str:
String str = "helloslkhellodjladfjhello"; String findStr = "hello"; int lastIndex = 0; int count = 0; while (lastIndex != -1 && lastIndex < str.length()) { lastIndex = str.indexOf(findStr, lastIndex); if (lastIndex != -1) count++; lastIndex += findStr.length(); } System.out.println(count);
Alternatively, you can use the StringUtils.countMatches method from the Apache Commons Lang library:
String str = "helloslkhellodjladfjhello"; String findStr = "hello"; System.out.println(StringUtils.countMatches(str, findStr));
This method simplifies the process of counting substring occurrences and ensures an efficient and reliable solution.
The above is the detailed content of How to Efficiently Count Substring Occurrences in Java?. For more information, please follow other related articles on the PHP Chinese website!