duanpin9531 2013-09-07 09:26
浏览 34

如何计算给定字符串中字符串的出现而不使用预定义的字符串函数?

Here is the small snippet to count the string occurrences of string without using string functions.

  <?php

$str ='1234567891222222222233333332';
$count = 0;
$ones='';
$twos='';
$threes='';

while(isset($str[$count])){
//echo $str[$count];

if($str[$count]== 1)
$ones += count($str[$count]);

if($str[$count]== 2)
$twos += count($str[$count]);

if($str[$count]== 3)
$threes += count($str[$count]);

++$count;
}
echo 'total number of 1\'s = '.$ones.'<br/>';
echo 'total number of 2\'s = '.$twos.'<br/>';
echo 'total number of 3\'s = '.$threes.'<br/>';
?>

Please can anyone shorter the code in efficient way...

  • 写回答

5条回答 默认 最新

  • douzhang6496 2013-09-07 09:30
    关注

    sounds like homework to me:

    $counters = array_fill(0,10,0);
    $count = 0;
    while(isset($str[$count])){
        $counters[$str[$count++]]++;
    }
    foreach($counters as $key => $value) {
        echo "Total number of {$key}s = {$value}", PHP_EOL;
    }
    

    or even using

    array_count_values(str_split($str));
    

    if str_split() is permitted

    评论

报告相同问题?