这是在不使用字符串函数的情况下计算字符串出现次数的小片段。
<?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/>';
?>
请任何人都能以有效的方式缩短代码......
答案 0 :(得分:2)
你可以这样做。我不确定你为什么要使用count()
,因为你可以增加它。
$count = 0;
$countSizes = array();
while(isset($str[$count++])) {
$countSizes[ $str[$count] ]++;
}
$countSizes
现在将具有与其索引相对应的字符串中每个数字的计数。
答案 1 :(得分:2)
如果您的号码范围为array_count_values
str_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
答案 2 :(得分: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()
答案 3 :(得分: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.'".';
}
答案 4 :(得分: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/>";
}
?>