How to count the number of occurrences of a substr

2019-01-20 20:03发布

问题:

Anybody can tell me about how to find the number of occurrence of substring in the given string without using the string function . for example the string is "when the men get the hen" and the result i expected is the substring 'he' occur 4 times in the given string.

回答1:

substr_count('when the men get the hen', 'he');

http://php.net/manual/en/function.substr-count.php



回答2:

Without using any string functions?

Is there any real point in restricting yourself to a set of functions that excludes those specially designed to do what you're trying to do?

$string = 'when the men get the hen';
$substring = 'he';

$cArr = explode($substring,$string);
$substring_count = count($cArr) - 1;


回答3:

Step through the string one character at a time

Check if the current character is an 'h'

If it is check if the next character is an 'e'

If it is an 'e', increase your counter by 1

Go back to step 1