我有字符串AABBBCCCDABBAACBB
,在这个我需要找到最多出现的字符,我怎么能找到这个?
在上面的字符串中它应该返回7 ad B来7次,即最多
$str = "AABBBCCCABB";
$strArray = count_chars($str,1);
foreach ($strArray as $key=>$value)
{
echo "The character <b>'".chr($key)."'</b> was found $value time(s)<br>";
//$highest=chr($key);
if(isset($highest) && $highest>chr($key))
{
$highest=chr($key);
}
}
echo "<br/><br/>Highest value is ::".$highest;
我试过上面的代码,
我试过但功能不完美,我应该使用php
的哪个功能?
答案 0 :(得分:2)
$string="AABBBCCCABB";
foreach (str_split($string) as $s){
if (isset($counts[$s])) continue;
$counts[$s]=substr_count($string, $s);
echo "The character <b>'" . $s . "'</b> was found ".$counts[$s]." time(s)<br>";
}
$maxs=array_keys($counts, max($counts));
echo "Highest value is ::'".$maxs[0];
答案 1 :(得分:2)
你不需要循环。使用array_search()
查找最重复值的键,并在其上使用chr()
:
$str = "AABBBCCCDABBAACBB";
$strArray = count_chars($str,1);
echo chr(array_search(max($strArray), $strArray));
输出:
B
答案 2 :(得分:0)
按您的方式解决您的代码:
$str = "AABBBCCCABB";
$strArray = count_chars($str,1);
$highest = $str[0];
$times = 0;
foreach ($strArray as $key=>$value){
echo "The character <b>'".chr($key)."'</b> was found $value time(s)<br>";
//$highest=chr($key);
if($times < $value)
{
$times = $value;
$highest=chr($key);
}
}
echo "<br/><br/>Highest value is ::".$highest;
但是使用Alma Do的答案会更好。
答案 3 :(得分:0)
您也可以使用max()
功能:
$str = "AABBBCCCABB";
$strArray = count_chars($str,1);
$highest = max($strArray);
foreach ($strArray as $key=>$value) {
echo "The character <b>'" . chr($key) . "'</b> was found $value time(s)<br>";
}
echo "<br/><br/>Highest value is ::" . $highest;
答案 4 :(得分:0)
尝试此解决方案,希望这有助于您解决。
$string = "AABBBCCCABB";
$letters = array_count_values(str_split($string));
$val = array_search(max($letters), $letters);
echo $val;
答案 5 :(得分:0)
试试这个..
echo maxCountChar("AABBBCCCDABBAACBB");
function maxCountChar($string){
foreach (str_split($string) as $s){
$counts[$s]=substr_count($string, $s);
}
$maxs=array_keys($counts, max($counts));
$num = substr_count($string, $maxs[0]);
return "The character <b>$maxs[0]</b> was found <b>$num</b> times";
}
<强>输出强>
The character B was found 7 times