首页 > 代码库 > 找出字符串中出现次数最多的字符,出现了几次都表示出来
找出字符串中出现次数最多的字符,出现了几次都表示出来
var a="AAAAAAAAWelcomeToQianfng";
var arr=new Array(52);
for(var i=0;i<arr.length;i++){
arr[i]=0;
}
//console.log(arr);//"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0"
for(var i=0;i<a.length;i++){
//a-----z 97---122 A---Z 65----90
if(/[a-z]/.test(a[i])){//xiao
var index=a.charCodeAt(i)-97;
//console.log(index);
arr[index]++;
}
if(/[A-Z]/.test(a[i])){//大
var index=a.charCodeAt(i)-65+26;
//console.log(index);
arr[index]++;
}
console.log(arr);
var maxnum=0; //次数
var numb=0;//
for(var j=0;j<arr.length;j++){
if(arr[j]>maxnum){
maxnum=arr[j]; //1 2 3
numb=j;
}
}
console.log(arr); //"1,0,1,0,10,1,1,0,1,0,0,1,1,2,2,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,1,0,0,0"
console.log(maxnum);
//console.log(numb);
var ch="";
if(numb<26){
ch+=String.fromCharCode(numb+97);
}else{
ch+=String.fromCharCode(numb+65-26);
}
console.log(ch)
}
找出字符串中出现次数最多的字符,出现了几次都表示出来