查找文本中出现次数最多的字符以及出现的次数

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>筛选出现次数最多的字符</title>
		<style type="text/css">
			.wrap{width:500px;height:300px;margin:0 auto;}
			textarea{color:green;font-family: "微软雅黑";font-size: 16px;display: block;margin: auto;width:500px;height:300px;}
			button{display:block;width:100px;height:45px;}
			#val{width:100%;color:#008000;font-family: "微软雅黑";font-size: 20px;font-weight: bold;};
		</style>
	</head>
	<body>
			<div class="wrap">
			<textarea rows="20" cols="90" id="txt"></textarea>
			<button id="btn">提取</button><br/><br/><br/>
			<div id="val">
			</div>
			</div>
		<script type="text/javascript">
		    var btn=document.getElementById("btn");
function extract()
{
	var str=document.getElementById("txt").value;
	if(str=="")
	{
		alert("请输入内容!");
		return false;
	}
	str=str.toString();
	var obj={},max=new Array();
	for(var i=0;i<str.length;i++)
	{
		if(obj[str[i]])
		{
			obj[str[i]]++;
			if(obj[str[i]]>obj[max[0]])
			{
				max.splice(0,max.length,str[i]);
			}
			else
			{
				if(obj[str[i]]==obj[max[0]]&&str[i]!=max[0])
				{
					max.push(str[i]);
				}
				else if(obj[str[i]]==obj[max[0]]&&str[i]==max[0])
				{
					max.splice(0,max.length,str[i]);
				}
			}
			
		}
		else
		{
			obj[str[i]]=1;
			if(i==0)		
			{
			max[0]=str[i];
			}
			else
			{
				if(obj[str[i]]==obj[max[0]]&&str[i]!=max[0])
				{
					max.push(str[i]);
				}
				else if(obj[str[i]]==obj[max[0]]&&str[i]==max[0])
				{
					max.splice(0,max.length,str[i]);
				}
			}
		}
	}
	document.getElementById("val").innerHTML="出现次数最多的字符为:"+max+"<br/><br/>"+"出现的次数为:"+obj[max[0]];
}
btn.onclick=function()
{
	extract();
}

		</script>
	</body>
</html>

欢迎分享本文,转载请保留出处:前端ABC » 查找文本中出现次数最多的字符以及出现的次数

分享到:更多 ()

发表评论 0