开发者

How to get the count of string 2 occurrence in string 1 without php built-in functions

How to get the count of string 2 occurrence in string 1 without php built-in functions.

Example:

$strone = "开发者_开发知识库Arun sukumar";
$strtwo = "a";

//Expected Output: 2


$strone = "Arun sukumar";
$strtwo = "uk";

//Expected Output: 1

I need to get the count without using any php built-in functions.

This is the question asked in a interview, is there any logic in that?


You need to take your needle, get the first char.. then iterate over each char of the haystack until you get match. Then take the next char of needle and check the next char of the haystack for a match... continue until you have the complete match for needle or until you fial to match a char.

hint: you can access the individual chars of a string by index with $string{0} where 0 is the zero based index of the char in the string.


$strone = 'arun sukumar';
$strtwo = 'a';

echo parsestr($strone, $strtwo);

function parsestr($strone, $strtwo)
{
    $len = 0;
    while ($strtwo{$len} != '') {
        $len++;
    }

    $nr = 0;

    while ($strone{$nr} != '')
    {
        if($strone{$nr} != ' ')
        {
            $data[$nr] = $strone{$nr};
        }
        $nr++;
    }

    $newdata = $data;

    if($len > 1)
    {
        $newdata = array();
        $j = 0;
        foreach($data as $val)
        {
            $str .= $val;
            if($j == ($len -1))
            {
                $newdata[] = $str;
                $str = '';
                $j = 0;
            }
            else
                $j++;
        }
    }
    $i = 0;

    foreach($newdata as $val)
    {
        if($val == $strtwo)
        {
            $i++;
        }
    }
    return $i;
}


Try this

$string = 'Arun sukumar'; 

$sub_string = 'a';

$count = 0;
for($i=0;$i < strlen($string); $i++){

    $flag = 0;
    $j=0;
    if(strtolower($string[$i]) == $sub_string[$j])
    {
        //echo "match";
        $flag = 1;
        $k = $i;
        for(;$j< strlen($sub_string); $j++){//echo "[".$j . $k."] $count $flag";
            if(strtolower($string[$k]) != $sub_string[$j]){
                $flag = 0;
                break;
            }
            $k++;
        }//echo "<br> $flag";
    }
    if($flag == 1){
        $count++;
        $flag = 0;
    }
}

echo $count;

?>


Not sure why you would not want to use the built-in PHP functions since they would be faster, but something like this would work:

<?php
$haystack = 'Arun sukumar';
$needle = 'a';

// you seem to want a case insensitive search, so do a strtolower first
$haystack = strtolower($haystack);
$hitCount = 0;
for ($i = 0; $i < strlen($haystack); ++$i) {
    if ($needle === substr($haystack, $i, strlen($needle))) {
        $hitCount++;
    }
}
echo 'Output: ' . $hitCount;
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜