函数来求bcde在这个字符串中出现的次数

2020-01-30T17:09:38

有这样一个字符串abcdefgkbcdefab......随机长度,写一个函数来求bcde在这个字符串中出现的次数

$str = "abceeedefdsafujdsklgjmrj89gu89eeefiodsaflkjdsafjhuigbeeejhndfiofgidsafndyeeeubhngihaf;odsa";
$tag = "eee";

function search($str, $need)
{
    $res      = [];
    $str_len  = strlen($str);
    $need_len = strlen($need);
    for ($i = 0; $i < $str_len; ++$i) {
        for ($n = 0; $n < $need_len; ++$n) {
            if (isset($str[$i + $n]) && $need[$n] != $str[$i + $n]) {
                break;
            }
            if ($n == $need_len - 1) {
                $res[] = $i;
            }
        }
    }
    return $res;
}

var_dump(search($str, $tag), count(search($str, $tag)));
当前页面是本站的「Baidu MIP」版。发表评论请点击:完整版 »