-1

我有字符串AABBBCCCDABBAACBB,在这我需要找到出现最多的字符,我怎么能找到这个?

在上面的字符串中,它应该返回 7 广告 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我应该使用哪个功能?

4

6 回答 6

2

你不需要一个循环。用于array_search()查找重复值最多的键,并chr()在其上使用:

$str = "AABBBCCCDABBAACBB";
$strArray = count_chars($str,1);
echo chr(array_search(max($strArray), $strArray));

输出:

B

演示!

于 2013-11-02T18:31:25.360 回答
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];
于 2013-11-02T18:26:43.750 回答
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;
于 2013-11-02T18:29:45.343 回答
0

试试这个解决方案,希望这可以帮助你解决。

$string  =  "AABBBCCCABB";
$letters = array_count_values(str_split($string));
$val = array_search(max($letters), $letters);
echo $val;
于 2013-11-02T18:31:27.400 回答
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
于 2013-11-02T18:31:38.697 回答
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的答案更好用。

于 2013-11-02T18:27:24.717 回答