简体   繁体   English

JavaScript字符串中多个子字符串的计数

[英]Count of multiple substrings in JavaScript string

I am receiving a tokenized string from the server in the form of status---delimiter---status where I may have up to 1000 statuses. 我正在以status --- delimiter --- status的形式从服务器接收一个标记化的字符串,其中我可能有多达1000个状态。 There are only 6 different possible values for status. 状态只有6种不同的可能值。 I am trying to find a way to search for all 6 at once and that gives me a count of each. 我试图找到一种方法来同时搜索所有6个,这给了我每个的计数。 I've come up with several less optimum ways of solving the issue but the best I could think of still effectively makes 2 full passes on the string and involves several substeps. 我已经提出了几种解决问题的不太理想的方法,但我能想到的最好的方法仍然有效地在字符串上进行了2次完整传递并涉及几个子步骤。 I looked at regX .match and capture groups but couldn't seem to find any way to make that work better then one status at a time. 我查看了regX .match和捕获组,但似乎无法找到任何方法使这项工作比一次一个状态更好。 I realize the performance difference wont be noticeable but now I just want to know, since in theory this should be doable (though maybe not with JavaScripts regX). 我意识到性能差异不会引人注意但现在我只想知道,因为理论上这应该是可行的(尽管可能不是JavaScripts regX)。

Example Set of statuses: [red,blue,green,orange,purple,pink] Delimiter (I can chose this): | 示例状态集:[红色,蓝色,绿色,橙色,紫色,粉红色]分隔符(我可以选择此项):| String: red|purple|green|red|blue|orange|purple|blue 字符串:红色|紫色|绿色|红色|蓝色|橙色|紫色|蓝色

Result: [red: 2, blue: 2, green: 1, orange: 1, purple, 2, pink 0] 结果:[红色:2,蓝色:2,绿色:1,橙色:​​1,紫色,2,粉红色0]

使用此答案中的 strtok迭代字符串一次,依次拉出每个“标记”(状态值),并随时增加计数。

Your question is a bit unclear. 你的问题有点不清楚。 This is what I'm assuming you're attempting to do (ie. ---delimiter--- is wrapped in a status): 这就是我假设你正在尝试做的事情(即---delimiter---被包裹在一个状态中):

var string = 'status1---delimiter---status1 asdf status1---delimiter---status1 asdf asdf fdsa status3---delimiter---status3 asdf status1---delimiter---status1 fdsa status1---delimiter--- asdf status5---delimiter---status5 status5---delimiter---status5 asdf status6---delimiter---status6 asdffdsa';
var matches = {}, re = /(status1|status2|status3|status4|status5|status6)---delimiter---\1/g, match;
while (match = re.exec(string)) {
    if (!matches.hasOwnProperty(match[1])) {
        matches[match[1]] = 1;
    } else {
        matches[match[1]] += 1;
    }
}
/*
 * matches = {
 *     status1: 3,
 *     status3: 1,
 *     status5: 2,
 *     status6: 1
 * }
 */

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM