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


How to count occurances of strings in given string wothout using a predefined 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/>';
?>

请任何人都可以以有效的方式缩短代码...

你可以

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

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

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

如果您的号码范围0-9,您可以使用array_count_valuesstr_split

$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
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.'".';
}
对我来说

听起来像是家庭作业:

$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()

使用:

<?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/>";  
}
?>