[英]JavaScript function to automatically count consecutive letters in a string
I am attempting (unsuccessfully) to write JavaScript function LetterCount to count the consecutive letters in a string (and not the total number). 我正在尝试 (不成功)编写JavaScript函数LetterCount来计算字符串中的连续字母(而不是总数)。
Ideally: LetterCount("eeeeeoooohhoooee") = [["e", 5],["o",3],["h",2],["o",3],["e",2]] 理想情况下:LetterCount(“eeeeeoooohhoooee”)= [[“e”,5],[“o”,3],[“h”,2],[“o”,3],[“e”,2]]
The following code attempts to count the number of consecutive letters in a string only when I already know what they are: 以下代码仅在我已经知道它们是什么时才尝试计算字符串中连续字母的数量:
function LetterCount(str) {
for (var i=0; i<str.length;i++) {
var arr1=[]; arr2=[]; arr3=[]; arr4=[]; arr5=[];
var e=0; o=0; h=0; o2=0; e2=0;
if(str[i]="e") {
arr1 += "e";
e++;
}
arr1.push(e);
if(str[i]="o") {
arr2 += "o";
o++;
}
arr2.push(o);
if(str[i]="h") {
arr3 += "h";
h++;
}
arr3.push(h);
if(str[i]="o") {
arr4 += "o";
o2++;
}
arr4.push(o2);
if(str[i]="e") {
arr5 += "e";
e2++;
}
arr5.push(e2);
}
return arr1.concat(arr2).concat(arr3).concat(arr4).concat(arr5);
}
In the code above, I need to first know what the letters in the string are, and how many of them are present, in what order. 在上面的代码中,我需要首先知道字符串中的字母是什么,以及它们中有多少字母以什么顺序存在。
INSTEAD: How do you write a function that will automatically recognize the letter themselves, and then return the count of consecutive letters. INSTEAD:你如何编写一个能自动识别字母的函数,然后返回连续字母的数量。 Would also be great if the answer is in the following format:
如果答案采用以下格式,也会很棒:
LetterCount("eeeeeoooohhoooee") = [["e", 5],["o",3],["h",2],["o",3],["e",2]]
Any help is much appreciated! 任何帮助深表感谢!
You can use a regular expression to match any letter followed by zero or more instances of the same letter. 您可以使用正则表达式匹配任何字母,后跟零个或多个相同字母的实例。
rx=/([a-zA-Z])\\1*/g; RX = /([A-ZA-Z])\\ 1 * /克;
Your example matches ["eeeee","oooo","hh","ooo","ee"]. 你的例子匹配[“eeeee”,“oooo”,“hh”,“ooo”,“ee”]。
Using map, return the initial letter and the number of occurences in a new array for each index. 使用map,返回每个索引的新数组中的首字母和出现次数。
function letterCount(str){
var s= str.match(/([a-zA-Z])\1*/g)||[];
return s.map(function(itm){
return [itm.charAt(0), itm.length];
});
}
letterCount("eeeeeoooohhoooee") letterCount( “eeeeeoooohhoooee”)
returned value: (Array) 返回值:(数组)
[["e",5],["o",4],["h",2],["o",3],["e",2]] [[ “E”,5],[ “○”,4],[ “H”,2],[ “○”,3],[ “E”,2]]
NOTES: 笔记:
returns an array of matches (repeated letters) or an empty array([]). 返回匹配数组(重复字母)或空数组([])。 Otherwise, if the string does not contain any letters an error would be thrown (from calling map on null).
否则,如果字符串不包含任何字母,则会抛出错误(从null调用map)。
\\1* is used to allow matching instances of a single letter with any or no sequential repetition. \\ 1 *用于允许单个字母的匹配实例与任何顺序重复或不重复。 '\\1+' would not match a single unrepeated letter.
'\\ 1+'与单个未重复的字母不匹配。
Array map expects a function and passes three arguments- the value at each index, the index number, and a reference to the entire array. 数组映射需要一个函数并传递三个参数 - 每个索引的值,索引号和对整个数组的引用。 In this case, only the value of each index is used, so we can ignore the other arguments.
在这种情况下,只使用每个索引的值,因此我们可以忽略其他参数。
This is my answer: 这是我的答案:
function LetterCount(str) {
var current, i = 0, l = str.length;
var outputArr = [];
while(i<l) {
current = str.charAt(i);
if(!i++ || outputArr[outputArr.length-1][0] !== current)
outputArr[outputArr.length] = [current, 1];
else outputArr[outputArr.length-1][1]++;
}
return outputArr;
}
As a modification to kennebec's (awesome) answer, so that the anonymous function isn't declared each time the parent function is called. 作为对kennebec(非常好)答案的修改,以便每次调用父函数时都不会声明匿名函数。 This is only to reference a better programming practice in comparison to pure simplicity (this is probably the most efficient method):
与纯粹的简单性相比,这只是为了引用更好的编程实践(这可能是最有效的方法):
var letterCount = (function(){
var r = /([A-z])\1*/g,
f = function(itm){
return [itm.charAt(0), itm.length];
};
return function letterCount(str){
return str.match(r).map(f);
};
}());
Actually "fixed" ["o",3]
to ["o",4]
;) 实际上“固定”
["o",3]
到["o",4]
;)
// node v0.10.31
// assert v1.3.0
var assert = require('assert');
function letterCount(str) {
var i = 0,
seq = 0,
results = [];
while (i < str.length) {
var current = str[i],
next = str[i + 1];
if (typeof results[seq] === 'undefined') {
results[seq] = [current, 0];
}
results[seq][1]++;
if (current !== next) {
seq++;
}
i++;
}
return results;
}
var actual = letterCount('eeeeeoooohhoooee');
var expected = [["e", 5],["o",4],["h",2],["o",3],["e",2]];
assert.deepEqual(actual, expected);
I'd use a map keyed on the character to store the count of consecutive chars and then build the output structure at the end. 我使用键入字符的地图来存储连续字符的数量,然后在结尾处构建输出结构。 I'm not sure I understand exactly what you mean by consecutive based on your example but you can tweak the logic to identify a consecutive number accordingly.
我不确定我根据你的例子确切地理解了你的意思,但是你可以通过调整逻辑来相应地识别一个连续的数字。
function LetterCount(str) {
var counts = {};
for (var i = 0, prevChar = null; i < str.length; i++) {
var char = str.charAt(i);
if(counts.hasOwnProperty(char) && char === prevChar) {
counts[char] = counts[char] + 1;
} else if (!counts.hasOwnProperty(char)) {
counts[char] = 0;
}
prevChar = char;
}
var res = [];
for (var char in counts) {
if (counts.hasOwnProperty(char)) {
res.push([char,counts[char]);
}
}
return res;
}
function LetterCount(text){
arr = [];
letter = text[0];
counter = 0;
for (c in text+' '){
if (text[c] != letter){
newArr = [letter, counter];
arr.push(newArr);
letter = text[c];
counter = 0;
}
counter += 1;
};
return arr;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.