您的位置:首页 > Web前端 > JavaScript

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

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

<!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>


思路是通过字符分割成数组,而字符的显示次数恰好是数组的长度减一,然后判断字符显示次数的大小。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: