【问题标题】:What is the most efficient way to go through string's chars in Javascript?在 Javascript 中遍历字符串字符的最有效方法是什么?
【发布时间】:2016-07-28 22:27:03
【问题描述】:

我看到有关于 SO 的类似问题,但我没有找到符合我特定目标的问题。

我开发了一个小函数,它通过一个字符串(比如说 10 到 160 个字符)循环提取

  • 通配符(例如 $1、$2、...) - 称为“特价商品”
  • 它们之间的字符串

要解析的字符串示例:“word1 word2 $1 word3 $2 word4 $3”。

输出示例:

{
    strings: [word1 word2, word3, word4],
    specialChars: 3
}

当然也有限制情况(没有通配符,只有1个通配符,通配​​符可以在字符串的开头或结尾)。

到目前为止我写的算法如下(在这个问题中,有一些问题需要修复,但我对效率比结果更感兴趣):

function parsestr(str: string) {
    let specialChars = [],
        plaintextParts = [],
        resultObject = {
            strings: [],
            specialChars: 0
        };

    // convert to char array and loop
    str.split('').forEach(function(c, i){
       if (c=='$') specialChars.push(i);
    });
    resultObject.specialChars = specialChars.length;

    // extract plain text parts
    if (specialChars.length == 0) return resultObject;

    // part before first wildcard
    if (specialChars[0]>0) plaintextParts.push(str.substr(0, specialChars[0]-1));
    // 2..N
    for (var i=1; i<specialChars.length-1; i++) {
        plaintextParts.push(str.substr(specialChars[i-1]+2, specialChars[i]-1));
    }
    // last part
    if (specialChars[specialChars.length-1]+1 < str.length-1)
        plaintextParts.push(str.substr(specialChars[specialChars.length-2]+2, specialChars[specialChars.length-1]-1));

    resultObject.strings = plaintextParts;
    return resultObject;
}

// call function and print output
var jsonString = "word1 word2 $1 word3 $2 word4 $3";
console.log(JSON.stringify(parseJsonString(jsonString)));

【问题讨论】:

  • 我相信这已经可以通过 JS O_o 中的内置正则表达式完成
  • 是的。 @MatíasFidemraizer 这正是如何做到的 ;-)

标签: javascript string performance typescript


【解决方案1】:

您可以只使用正则表达式:

let str = "word1 word2 $1 word3 $2 word4 $3";
let regex = /\$[0-9]/;
let strSplit = str.split(regex);
console.log(JSON.stringify(strSplit)); // ["word1 word2 ", " word3 ", " word4 ", ""]

如果您不想要最后一个空字符串,您可以随时将其 s(p) 剪掉。

因此,如果您想要“特殊字符”的数量,您只需将结果 strSplit 的长度减去一个即可。

【讨论】:

  • 还有一件事:因为我需要两个字符串(word1 word2、word3、...)和 where(即可能有 2 个特价 $1、$2 连续),所以特价是。我怎样才能跟踪它?
  • 什么意思?考虑再问一个问题并告诉我
  • 没关系。我想到了。谢谢你的回答!
【解决方案2】:

就效率而言,这似乎是一种微优化,尤其是对于不超过 160 个字符的字符串。让你的代码以一种简洁易懂的方式工作比优化每个操作的效率更重要。

在优化您的代码时,请尝试使您的通用解决方案更高效,然后再优化细节。假设这个函数不存在于真空中,试着关注应用本身的性能,并在优化字符串操作之类的东西之前找出实际的性能瓶颈在哪里。

【讨论】:

    猜你喜欢
    • 2012-03-04
    • 2013-05-17
    • 2012-10-29
    • 2010-09-16
    • 2021-09-20
    • 1970-01-01
    • 2013-05-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多