javascript 计算字符串中重复的字母
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30512744/
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
Count repeated letters in a string
提问by Olena Horal
I'm stuck with the following problem: I need to find repeated characters in a string. Basically what I want is regular expression that will match like that
我遇到了以下问题:我需要在字符串中找到重复的字符。基本上我想要的是像这样匹配的正则表达式
hello - ["ll"];
here - ["ee"];
happiness - ["pp","ss"];
pupil - ["pp"];
I have the one that matches consecutive repeated characters
我有一个匹配连续重复字符的
/([a-z])+/g
Also the one that will match repeated chars and everything between them like this one
也是将匹配重复字符以及它们之间的所有内容的那个
/([a-z])(?:.*)+/g
But cant figure out the correct one.
但想不出正确的。
回答by dawg
You can use
您可以使用
([a-zA-Z]).*()
Since you have clarified that you are looking for a solution that will handle something other than double letters in a string, you should use a non-regex approach such as:
由于您已经澄清您正在寻找一种解决方案来处理字符串中的双字母以外的其他内容,因此您应该使用非正则表达式方法,例如:
Build an associative array with the count of the characters in the string:
使用字符串中的字符数构建关联数组:
var obj={}
var repeats=[];
str='banana'
for(x = 0, length = str.length; x < length; x++) {
var l = str.charAt(x)
obj[l] = (isNaN(obj[l]) ? 1 : obj[l] + 1);
}
console.log(obj)
Prints
印刷
{ b: 1, a: 3, n: 2 }
Then build an array of your specifications:
然后构建您的规格数组:
for (var key in obj) {
if (obj.hasOwnProperty(key) && obj[key]>1) {
repeats.push(new Array( obj[key]+ 1 ).join( key ));
}
}
console.log(repeats)
Prints:
印刷:
[ 'aaa', 'nn' ]
回答by deadboy
var obj = {};
var str = "this is my string";
for (var i = 97; i < 97 + 26; i++)
obj[String.fromCharCode(i)] = 0;
for (var i = 0; i < str.length; i++) {
obj[str.charAt(i).toLowerCase()]++;
}
From there you can say obj["a"]
to get the number of occurrences for any particular letter.
从那里你可以说obj["a"]
得到任何特定字母的出现次数。
回答by emartinelli
For your scenario you second solution seems better. You can get the second letter by other capture group
对于您的情况,您的第二个解决方案似乎更好。您可以通过其他捕获组获取第二个字母
Regex you be (it is your 2nd RegEx with more one capture group):
你是正则表达式(这是你的第二个正则表达式,有更多一个捕获组):
/([a-z])(?:.*)()+/g
var re = /([a-z])(?:.*)()+/g;
var str = ['hello', 'here', 'happiness', 'pupil'];
var m;
var result = new Array();
for(var i = 0; i < str.length; i++) {
result[i] = str[i] + "->";
while ((m = re.exec(str[i])) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
result[i] += m[1];
result[i] += m[2] + ",";
}
}
document.getElementById("results").innerHTML = result.join("</br>");
<div id="results"></div>
回答by SpenserJ
More complicated than a RegExp solution, however it properly handles banana
and assassin
, where there are two overlapping groups of characters.
比 RegExp 解决方案更复杂,但它可以正确处理banana
和assassin
,其中有两个重叠的字符组。
This does make use of array.map, array.filter, and array.reduce, which means this exact solution doesn't support <=IE8, however it can be polyfilled quite easily.
这确实使使用array.map,array.filter和array.reduce,这意味着此确切解决方案不支持<= IE8,但是它可以很容易地polyfilled。
function findDuplicateCharacters(input) {
// Split the string and count the occurrences of each character
var count = input.split('').reduce(function(countMap, word) {
countMap[word] = ++countMap[word] || 1;
return countMap;
}, {});
// Get the letters that were found, and filter out any that only appear once.
var matches = Object.keys(count)
.filter(function (key) { return (count[key] > 1); })
// Then map it and create a string with the correct length, filled with that letter.
.map(function (key) {
return new Array(count[key] + 1).join(key);
});
return matches;
}
var results = ['hello', 'here', 'happiness', 'pupil', 'banana'].map(findDuplicateCharacters);
document.getElementById("results").innerHTML = results.join('<br />');
<div id="results"></div>
回答by Viswa
var re = /([a-z])(?:.*)()+/g;
var str = ['aaaccbcdd'];
var m;
var result = new Array();
for(var i = 0; i < str.length; i++) {
result[i] = str[i] + "->";
while ((m = re.exec(str[i])) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
result[i] += m[1];
result[i] += m[2] + ",";
}
}
document.getElementById("results").innerHTML = result.join("</br>");
<div id="results"></div>
回答by Dominic Amal Joe F
This method also works well!!
这个方法也很好用!!
let myString = 'abababc';
let result = {};
for (let str of myString) {
result[str] = result.hasOwnProperty(str) ? result[str] + 1 : 1;
}
console.log(result);
The result will be like this {a: 3, b: 3, c: 1}
结果将是这样的{a: 3, b: 3, c: 1}