【javascript】查找字符串中显示次数最多的字符及次数

昨天群里有人问如何查找字符串中显示次数最多的字符及次数,其实网上有很多种方法可以实现,今天抽空也写了一个。

<!DOCTYPE HTML>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <title>查找字符串中显示次数最多的字符及次数</title>
    <style type="text/css">
    p{font:36px SimSun;line-height:36px;}
    </style>
</head>
<body>
    <p id="showStr"></p>
    <p id="showCount"></p>
</body>
</html>
<script type="text/javascript">
window.onload = function(){
    var oDiv = document.getElementById('showStr');
    var oDiv2 = document.getElementById('showCount');
    var str = 'lasdjfowqefulasddfjqseasdffe';
    var temp = temp2 = '';
    var count = 0;
    
    for(var i = 0; i < str.length; i++){
        temp = str.charAt(i);
        if((str.split(temp).length - 1) > count){
            count = str.split(temp).length - 1;
            temp2 = temp;
        }
    }
    oDiv.innerHTML = str;
    oDiv2.innerHTML = '显示次数最多的是 ' + temp2 + ',显示次数是 ' + count + '';
};
</script>

思路是通过字符分割成数组,而字符的显示次数恰好是数组的长度减一,然后判断字符显示次数的大小。

posted @ 2012-12-19 10:27  朱羽佳  阅读(673)  评论(3编辑  收藏  举报
回顶部