看看有没有更好的法子

WBOY
Release: 2016-06-23 13:50:14
Original
749 people have browsed it

刚在技术群看到一条N个钟前的问题:
用PHP如何找出在一个字符串中出现最多的字符

我的思路是先将字符串侵害成数组,通过array_count_values得到元素个数统计,排序,取最顶那个为最多次数,然后可能有多个相同最多次数,for循环找出来..

$testStr = 'rewruo ewjrewm' . PHP_EOL . 'hcywer国bg gfaaf d中国国国s国rew';$testStr = preg_replace('/\s/', '', $testStr);preg_match_all('/./u', $testStr, $strList);$charCount = array_count_values($strList[0]);arsort($charCount);$maxCount = current($charCount);foreach($charCount as $char => $count){	if($count < $maxCount){		break;	}	echo $char . '出现了 ' . $count . ' 次<br />';}
Copy after login


回复讨论(解决方案)

既然都用 array_count_values ,用 max 求交集就是了,不必循环

你都arsort了,直接echo key($charCount); 就是出现最多的字符了。

既然都用 array_count_values ,用 max 求交集就是了,不必循环




你都arsort了,直接echo key($charCount); 就是出现最多的字符了。


我循环是为了将其他同属最多次数的字符也输出来..按照你们的做法只输出了其中一个而已呢


既然都用 array_count_values ,用 max 求交集就是了,不必循环




你都arsort了,直接echo key($charCount); 就是出现最多的字符了。


我循环是为了将其他同属最多次数的字符也输出来..按照你们的做法只输出了其中一个而已呢


你没试过吧?交集啊,array_intersect,先去试一下看看结果~

你没试过吧?交集啊,array_intersect,先去试一下看看结果~


求代码,我的代码求出结果如下:

r出现了 5 次
w出现了 5 次
国出现了 5 次
e出现了 5 次

因为有4个相同次数并且是最多次数的字符

已经没有都少简化的余地了

$testStr = 'rewruo ewjrewm' . PHP_EOL . 'hcywer国bg gfaaf d中国国国s国rew';$testStr = preg_replace('/\s/', '', $testStr);preg_match_all('/./u', $testStr, $strList);$strList = array_count_values($strList[0]);$r = array_keys($strList, $m = max($strList));echo join($t=" 出现了 $m 次<br />", $r).$t;
Copy after login
r 出现了 5 次
e 出现了 5 次
w 出现了 5 次
国 出现了 5 次

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!