Home > Java > javaTutorial > Why Doesn't My Substring Counting Algorithm Halt?

Why Doesn't My Substring Counting Algorithm Halt?

Mary-Kate Olsen
Release: 2024-12-15 20:31:10
Original
367 people have browsed it

Why Doesn't My Substring Counting Algorithm Halt?

Why is the given algorithm not halting?

In the provided algorithm, an attempt is made to find the number of occurrences of a substring in a string. However, the algorithm is designed to continue until the last index of the substring in the string becomes -1. This condition will never be met because the last index is always being updated by adding the length of the substring to it. As a result, the algorithm will keep searching for the substring indefinitely, never terminating.

Using Apache Commons Lang for Substring Counting

An alternative approach to counting substring occurrences is to utilize the StringUtils.countMatches method from Apache Commons Lang. This method takes a string and a substring as arguments and returns the number of times the substring appears in the string. Using this method, the original problem can be resolved with the following code:

String str = "helloslkhellodjladfjhello";
String findStr = "hello";

System.out.println(StringUtils.countMatches(str, findStr));
Copy after login

This code outputs:

3
Copy after login

which correctly counts the occurrences of the substring "hello" in the string "helloslkhellodjladfjhello".

The above is the detailed content of Why Doesn't My Substring Counting Algorithm Halt?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template