给定一个字符串,找出出现次数最多的字符

let str = 'abcdefabcdefabcdeadfkjafd';
let obj = {};

for (let index = 0; index < str.length; index++) {
    if (obj[str[index]]) {
        obj[str[index]]++
    }else{
        obj[str[index]]=1
    }
   
}


console.log(obj); //将字符串整理成对象
let max=0
for (const key in obj) {
    if (max<obj[key]) {
       max=obj[key]
       
    }
}
console.log(max)// 找出出现最多次数

for (const key in obj) {
    if (obj[key]==max) {
        // 输出结果
        console.log('最多的字符是'+key)
        console.log('出现次数是'+max)
       
    }
}
posted @ 2023-02-23 12:59  小白字太白  阅读(64)  评论(0编辑  收藏  举报