在字符串javascript中查找最常见的字符 [英] Finding the most frequent character in a string javascript

查看:84
本文介绍了在字符串javascript中查找最常见的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下字符串35538​​5。我需要一个简单的JavaScript,可以告诉我最常提到的字符是5.提前谢谢你。

Assuming I have the following string "355385". I need a simple JavaScript that can tell me that the most mentioned character is 5. Thank you in advance.

我试过这个但没有结果。

I tried with this one but no results.

var exp = '355385' ;

var exps =exp.split("");

var expCounts = { };

for (var i=0;i<exp.length;i++)

{expCounts["_" + exps[i]] = (expCounts["_" + exps[i]] || 0) + 1 ;

if (expCounts==3) exps=exps[i]; }; exps;


推荐答案

这将遍历字符串中的每个字符并保持跟踪每个角色的数量和具有最大数量的角色:

This will loop over every character in the string and keep track of each character's count and the character with the maximum count:

var exp = '3553853335' ;
var expCounts = {};
var maxKey = '';
for(var i = 0; i < exp.length; i++)
{
    var key = exp[i];
    if(!expCounts[key]){
     expCounts[key] = 0;
    }
    expCounts[key]++;
    if(maxKey == '' || expCounts[key] > expCounts[maxKey]){
        maxKey = key;
    }
}

console.debug(maxKey + ":" + expCounts[maxKey]);

这篇关于在字符串javascript中查找最常见的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆