如何得到一个字符串中各个字符出现的次数?


从OutOfMemory上看到的一个题目,然后看了看其中的代码,结合自己之前的经验理解了一下,觉得代码不错,就放上来了:

<?php
$str="asdfgfdas323344##$\$fdsdfg*$**$*$**$$443563536254fas";	//任意长度字符串

//解法一(最方便的解法)
$arr=str_split($str);
$arr=array_count_values($arr);
arsort($arr);
print_r($arr);

//解法二(用字符本身作为数组下标)
$arr=str_split($str);
$con=array();
foreach ($arr as $v) {
	if (!@$con[$v]) {
		@$con[$v]=1;
	} else {
		@$con[$v]++;
	}
}
arsort($con);
print_r($con);

//解法三
$arr=str_split($str);
$unique=array_unique($arr);
foreach ($unique as $a){
	$arr2[$a]=substr_count($str, $a);
}
arsort($arr2);
print_r($arr2);

执行效果如下:

C:>php php_str_char_count.php
Array
(
[3] => 6
[*] => 6
[$] => 6
[4] => 5
[a] => 3
[5] => 3
[f] => 3
[s] => 3
[6] => 2
[2] => 2
[d] => 2
[#] => 2
[] => 1
[g] => 1
)
Array
(
[3] => 6
[*] => 6
[$] => 6
[4] => 5
[a] => 3
[5] => 3
[f] => 3
[s] => 3
[6] => 2
[2] => 2
[d] => 2
[#] => 2
[] => 1
[g] => 1
)
Array
(
[3] => 6
[*] => 6
[$] => 6
[4] => 5
[a] => 3
[5] => 3
[f] => 3
[s] => 3
[6] => 2
[2] => 2
[d] => 2
[#] => 2
[] => 1
[g] => 1
)

上面的那段代码非常精简,下面相当于是对应的繁体版的:

<?php
//PHP几个函数的使用
function countStr($str){
    $str_array=str_split($str);
    $str_array=array_count_values($str_array);
    arsort($str_array);
    return $str_array;
}
$str="asdfgfdas323344##$\$fdsdfg*$**$*$**$$443563536254fas";
print_r(countStr($str));


//用字符的值作为数组下标进行统计
function countStr2($str){
    $str_array=str_split($str);
    $result_array=array();
    foreach($str_array as $value){//根据字符之前是否出现过来赋值,没有出现设置为1,否则就自加1
        if(!$result_array[$value]){
            $result_array[$value]=1;
        }else{
            $result_array[$value]++;
        }
    }
    arsort($result_array);
    return $result_array;
}
$str="asdfgfdas323344##$\$fdsdfg*$**$*$**$$443563536254fas";
var_dump(countStr2($str));


//这个方法纯粹是解法一的蹩脚版本,先找出所有字符的总类(array_unique),然后再一个一个用substr_count函数统计
function countStr3($str){
	$str_array=str_split($str);
	$unique=array_unique($str_array);
	$result_array=array();
	foreach ($unique as $v){
		$result_array[$v]=substr_count($str,$v);
	}
	arsort($result_array);
	return $result_array;
}
$str="asdfgfdas323344##$\$fdsdfg*$**$*$**$$443563536254fas";
var_dump(countStr3($str));
?>

 


发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注