显示字符 'e' 在字符串中每次出现的位置

show the location of each occurence of the character 'e' in a string

得出答案。滚动到底部

我在尝试显示此字符时遇到问题。大多数情况下,我已经设置了代码结构,但我无法在数组中存储正确的值。卡住并筋疲力尽!

wordString = 'i, always, have, fruit, for, breakfast, consisting, of, a, small, fruit, bowl, with, yogurt, on, top, of, the, fruit, but, if, it, is, doughnuts, I, always, have, two, sometimes, they, have, sprinkles, and, sometimes, not, i, never, have, cereal, or, eggs, this, breakfast, regimen, is, very, healthy, especially, the, doughnuts.';
var wordPosition = [];

var letterAppearance = wordString.match(/e/g);

var positionStart = 0;

for(i = 0; i <= letterAppearance.length; i++) {

    positionStart = wordPosition[i];

    if(positionStart === 0) {
        positionString = wordString.substr(positionStart, wordString.length)
    } else {
        positionString = wordString.substr(wordPosition[i], wordString.length)
    }

    wordPosition[i] = positionString.indexOf('e');

}

感谢您提前的帮助

编辑

好的,所以我在这方面做了更多的工作,并且有一些更简单的东西,但还没有让它工作。除了数组中的第一对

之外,我的值不太正确
var wordPosition = [];
var letterAppearance = wordString.match(/e/g);
var positionStart = 0;

for( i = 0; i <= letterAppearance.length; i++){

wordPosition[i] = wordString.indexOf('e')+ positionStart;
positionStart = wordPosition[i];
}

这是我得到的值。

14,28,42,56,70,84,98,112,126,140,​​154,168,182,196,210,224,238,252,266,280,294,308,322,336,350,364

找到编辑答案

好的,在进一步研究之后,我得到了正确的答案代码。这是最简单的形式。

locations = " letter 'e' occurs at locations: ";
for (i = 0; i <= wordString.length; i++){
    character = wordString.substr(i,1);
    if(character === 'e'){
        locations = locations + i.toString() + ",";
    }
}

我认为只搜索一些 'e' 个职位太复杂了。你可以试试这个:

for (int i=0; i < /*string lenght*/ ; i++)

    if (/*String char at i*/ == 'e')
        /*Store position */

好的,经过更多的研究,我找到了最简单形式的答案。

locations = " letter 'e' occurs at locations: ";
for (i = 0; i <= wordString.length; i++){
    character = wordString.substr(i,1);
    if(character === 'e'){
        locations = locations + i.toString() + ",";
    }
}

这是输出。 字母 'e' 出现在以下位置:14,31,108,160,171,175,181,188,198,210,214,227,229,236,240,242,251,265,275,279,288,294,302,305,316,

你可以试试这个:

var str = "scissors";
var indices = [];
for(var i=0; i<str.length;i++) {
    if (str[i] === "s") indices.push(i+1);
}