获取字符串中重复的字符数 [英] Get duplicate characters count in a string
问题描述
任何人都可以帮助我获取javascript中给定字符串中重复字符的计数.
Can anyone help me to get the count of repeated characters in a given string in javascript.
例如,
"abccdef" -> 1 (Only "c" repeated)
"Indivisibilities" -> 2 ("i" and "s" repeated)
谢谢
推荐答案
这是一个有趣的问题.我们可以做的是使用 String.toLowerCase
将字符串转换为小写,然后在"
上分割,这样我们得到了一个字符数组.
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.
然后我们将使用 Array.sort
对它进行排序.排序后,我们将使用 Array.join
将其加入.然后,我们可以使用正则表达式/(.)\ 1 +/g
,这实际上意味着匹配一个字母和相同的后续字母.
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+/g
which essentially means match a letter and subsequent letters if it's the same.
当我们在声明的正则表达式中使用 String.match
时,我们将得到一个数组,其长度就是答案.还使用一些 try ... catch
返回 0
,以防匹配返回 null
并导致 TypeError
.
When we use String.match
with the stated regex, we will get an Array, whose length is the answer. Also used some try...catch
to return 0
in case match returns null
and results in TypeError
.
function howManyRepeated(str){
try{ return str.toLowerCase().split("").sort().join("").match(/(.)\1+/g).length; }
catch(e){ return 0; } // if TypeError
}
console.log(howManyRepeated("Indivisibilities")); // 2
这篇关于获取字符串中重复的字符数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!