循环遍历字符串以查找多个索引

2024-03-10

我试图找出循环字符串并查找某个字母的所有索引的最有效方法。

我用过$word_or_phrase.indexOf( $letter );查找某个字母的单个索引,但该字母位于$word_or_phrase多次。最有效的方法是构建一个包含所有索引的数组,直到.indexOf返回-1?或者你建议我如何找到所有索引?

我已经花了时间发现了这个:Javascript string.search() 多个实例 https://stackoverflow.com/questions/6825492/javascript-str-search-multiple-instances

这是可行的,但对我来说,在处理超过 2 个索引时似乎效率不高。如果我有 10 个怎么办?

感谢您提前的建议!


正如您发布的 StackOverflow 链接中的答案所示,您可以使用第二个参数indexOf定义搜索在字符串中的开始位置。您可以使用此技术继续循环字符串,以获取所有匹配子字符串的索引:

function getMatchIndexes(str, toMatch) {
    var toMatchLength = toMatch.length,
        indexMatches = [], match,
        i = 0;

    while ((match = str.indexOf(toMatch, i)) > -1) {
        indexMatches.push(match);
        i = match + toMatchLength;
    }

    return indexMatches;
}

console.log(getMatchIndexes("asdf asdf asdf", "as"));

DEMO: http://jsfiddle.net/qxERV/ http://jsfiddle.net/qxERV/

另一种选择是使用正则表达式来查找所有匹配项:

function getMatchIndexes(str, toMatch) {
    var re = new RegExp(toMatch, "g"),
        indexMatches = [], match;

    while (match = re.exec(str)) {
        indexMatches.push(match.index);
    }

    return indexMatches;
}

console.log(getMatchIndexes("asdf asdf asdf", "as"));

DEMO: http://jsfiddle.net/UCpeY/ http://jsfiddle.net/UCpeY/

另一种选择是手动循环字符串的字符并与目标进行比较:

function getMatchIndexes(str, toMatch) {
    var re = new RegExp(toMatch, "g"),
        toMatchLength = toMatch.length,
        indexMatches = [], match,
        i, j, cur;

    for (i = 0, j = str.length; i < j; i++) {
        if (str.substr(i, toMatchLength) === toMatch) {
            indexMatches.push(i);
        }
    }

    return indexMatches;
}

console.log(getMatchIndexes("asdf asdf asdf", "as"));

DEMO: http://jsfiddle.net/KfJ9H/ http://jsfiddle.net/KfJ9H/

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

循环遍历字符串以查找多个索引 的相关文章

随机推荐