2013-11-02 74 views
-1

我有字符串AABBBCCCDABBAACBB,在這個我需要找到最多的字符,我怎麼能找到這個?大多數情況下使用php函數的字符串中的字母

在上面的字符串中它應該返回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功能?

+0

「功能是不完美」 是一個問題的_really_差描述。請儘量提供至少_little_ bit更多關於_how_代碼沒有做你想做的事情的信息。 (也就是說,我在你的代碼中看到了一些明顯的錯誤,所以只是「不返回正確的值」在這個特例中就是一個適當的描述。) –

回答

2

你並不需要爲這個循環。使用​​找到最重複值的關鍵,並在其上使用chr()

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

輸出:

B 

Demo!

+0

...作爲答案接受,我標記了一個錯誤,所以這個標記不見了 – anam

+0

@simmisimmi:很高興我能幫上忙。僅供參考:您不能[接受](http://meta.stackexchange.com/a/5235/220538)多個答案。 :) –

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]; 
+0

爲什麼你改變你的答案>> ???事件正在發揮作用? – anam

+1

請不要對正在幫助的人大喊大叫。 –

+0

不要大聲說這只是錯誤上限......我正在嘗試他的代碼...... @ popnoodles thnx buddy – anam

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; 

但阿爾瑪做的答案是更好地使用。

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; 
0

嘗試這種解決方案,希望這可以幫助你解決。

$string = "AABBBCCCABB"; 
$letters = array_count_values(str_split($string)); 
$val = array_search(max($letters), $letters); 
echo $val; 
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 
相關問題