0

这是在不使用字符串函数的情况下计算字符串出现次数的小片段。

  <?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/>';
?>

请任何人都可以有效地缩短代码...

4

5 回答 5

2

你可以这样做。我不确定你为什么使用count(),因为你可以增加它。

$count = 0;
$countSizes = array();

while(isset($str[$count++])) {
    $countSizes[ $str[$count] ]++;
}

$countSizes现在将拥有与其索引相对应的字符串中每个数字的计数。

于 2013-09-07T09:33:34.920 回答
2

您可以使用array_count_valuesstr_split如果您的数字范围0-9

$result = array_count_values(str_split($str));

输出

var_dump($result);

array (size=9)
  1 => int 2
  2 => int 12
  3 => int 8
  4 => int 1
  5 => int 1
  6 => int 1
  7 => int 1
  8 => int 1
  9 => int 1
于 2013-09-07T09:35:26.490 回答
0

对我来说听起来像是家庭作业:

$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;
}

甚至使用

array_count_values(str_split($str));

如果允许 str_split()

于 2013-09-07T09:30:43.860 回答
0
for($i=1;$i<=3;$i++){
    preg_match_all ( $strn , $i, $matches);
    //preg_match_all stores the found values in $matches, you can count them easily...
    echo 'There is '.count($matches).' "'.$i.'".';
}
于 2013-09-07T09:33:22.797 回答
0

利用:

<?php
$str ='1234567891222222222233333332';

$i=0;
$char1 = $str[$i];
$isExists = array();
$found_array = array();
while(!empty($char1)) {
    if(in_array($char1, $isExists)) { 
        $i++;
        $char1 = isset($str[$i]) ? $str[$i] : '';
        continue; 
    };
    $count = 0;
    $j=0;
    $char2 = $str[$j];
    while(!empty($char2)) {
        //echo "$char1 = $char2<br>";
        if($char1==$char2) $count++;
        $j++;
        $char2 = isset($str[$j]) ? $str[$j] : '';
    }
    $isExists[] = $char1;
    $found_array[$char1] = $count;
    $i++;
    $char1 = isset($str[$i]) ? $str[$i] : '';
}

foreach($found_array as $char=>$count) {
    echo "total number of $char's = $count <br/>";  
}
?>
于 2013-09-07T10:03:09.450 回答