javascript 获取字符串中的重复字符数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28807016/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 09:36:11  来源:igfitidea点击:

Get duplicate characters count in a string

javascriptstring

提问by Naveen Krishna

Can anyone help me to get the count of repeated characters in a given string in javascript.

谁能帮我获取javascript中给定字符串中重复字符的数量。

For example,

例如,

"abccdef" -> 1 (Only "c" repeated)

"Indivisibilities" -> 2 ("i" and "s" repeated)

Thank You

谢谢

回答by iamsuman

You can use like this

你可以这样使用

function getFrequency(string) {
var freq = {};
for (var i=0; i<string.length;i++) {
    var character = string.charAt(i);
    if (freq[character]) {
       freq[character]++;
    } else {
       freq[character] = 1;
    }
}

return freq;
};

getFrequency('Indivisibilities');

回答by Amit Joki

This is an interesting problem. What we can do is turn the string to lower case using String.toLowerCase, and then split on "", so we get an array of characters.

这是一个有趣的问题。我们可以做的是使用 将字符串转换为小写String.toLowerCase,然后拆分为"",因此我们得到一个字符数组。

We will then sort it with Array.sort. After it has been sorted, we will join it using Array.join. We can then make use of the regex /(.)\1+/gwhich essentially means match a letter and subsequent letters if it's the same.

然后我们将用 对其进行排序Array.sort。排序后,我们将使用Array.join. 然后我们可以使用正则表达式/(.)\1+/g,这基本上意味着匹配一个字母和后续字母(如果相同)。

When we use String.matchwith the stated regex, we will get an Array, whose length is the answer. Also used some try...catchto return 0in case match returns nulland results in TypeError.

当我们使用String.match指定的正则表达式时,我们将得到一个数组,其长度就是答案。还使用 sometry...catch返回0,以防匹配返回null并导致TypeError.

function howManyRepeated(str){
   try{ return str.toLowerCase().split("").sort().join("").match(/(.)+/g).length; }
   catch(e){ return 0; } // if TypeError
}
console.log(howManyRepeated("Indivisibilities")); // 2