【问题标题】:how can I find the index for each time a char appears in a string (Javascript)?每次字符出现在字符串(Javascript)中时,如何找到索引?
【发布时间】:2017-12-29 10:09:43
【问题描述】:

您好,我正在尝试识别特定字符每次位于字符串中时的索引,并提供检测到的次数。

我想到的一种方法基本上是使用 (str.replace(/[^char]/g, "").length) 查找它在字符串中的次数,然后使用 str.lastIndexOf("char") 并在从该索引中删除字符并再次检查它之后创建一个新字符串,直到没找到。

但是我认为这不是最有效的方法,所以如果您有更好的方法,请告诉我?

假设:var str = "123456789017899199999100001",我们需要每个 1 的 index 以及在字符串中找到它的次数。

【问题讨论】:

  • str.match(/1/g).length ?

标签: javascript string char


【解决方案1】:

您可以为值及其索引创建一个哈希表。然后将数组的长度作为计数。

var string = "123456789017899199999100001",
    positions = Object.create(null);
    
[...string].forEach((v, i) => (positions[v] = positions[v] || []).push(i));

console.log(positions[1]);
console.log(positions[1].length);
console.log(positions);
.as-console-wrapper { max-height: 100% !important; top: 0; }

任何字符串的解决方案。

var string = "123456789017899199999100001",
    positions = [],
    index = -1,
    search = "99";
    
while ((index = string.indexOf(search, index + search.length)) !== -1) {
    positions.push(index);
}

console.log(positions);
console.log(positions.length);
.as-console-wrapper { max-height: 100% !important; top: 0; }

【讨论】:

  • 感谢您的回答,这是一个不错的方法。我该如何修改它,比如说我是否想在每次找到 99 时检查?
  • 它想要的结果是什么?
  • 每个99检测到的起始索引和99被找到的次数
【解决方案2】:

对这样的任务使用正则表达式是多余的,你是对的,它可以通过更简单的方式线性遍历字符串:

function count(str, char) {
    var rval = {indices:[], count:0};
    for(var i=0; i<str.length; i++) {
        if (str[i] === char) {
            rval.indices.push(i);
            rval.count++;
        }
    }
    return rval;
}

那么对于你的字符串它会产生:

count(str,'1') // {indices:[0,10,15,21,26],count:5}

您也可以简单地返回索引数组,其长度是出现的总次数

【讨论】:

    猜你喜欢
    • 2016-11-21
    • 2012-03-23
    • 2011-03-25
    • 2021-07-29
    • 1970-01-01
    • 2021-11-09
    • 1970-01-01
    • 1970-01-01
    • 2011-03-14
    相关资源
    最近更新 更多