从strtok在一个字符串解析空标记 [英] Parse empty tokens from a string with strtok
问题描述
我的应用程序会产生类似下面的字符串。我需要分隔成各个值之间的解析值。
My application produces strings like the one below. I need to parse values between the separator into individual values.
2342|2sd45|dswer|2342||5523|||3654|Pswt
我使用 strtok的
来做到这一点的一个循环。第五道理,我越来越5523.但是,我需要考虑两个分隔符 ||
之间的空价值。 5523应该是第六代币,按我的要求。
I am using strtok
to do this in a loop. For the fifth token, I am getting 5523. However, I need to account for the empty value between the two separators ||
as well. 5523 should be the sixth token, as per my requirement.
token = (char *)strtok(strAccInfo, "|");
for (iLoop=1;iLoop<=106;iLoop++) {
token = (char *)strtok(NULL, "|");
}
有什么建议?
推荐答案
在这种情况下,我经常preFER一个 P2 =和strchr(P1,'|')
循环使用的memcpy(S,P1,P2-P1)
里面。它速度快,不破坏输入缓冲区(因此它可与为const char *
使用),是真正便携(即使在嵌入式)。
In that case I often prefer a p2 = strchr(p1, '|')
loop with a memcpy(s, p1, p2-p1)
inside. It's fast, does not destroy the input buffer (so it can be used with const char *
) and is really portable (even on embedded).
这也是折返; strtok的
不是。 (顺便说一句:。折返无关与多线程 strtok的
与嵌套循环已经打破了一个可以使用 strtok_r
但它不是为便携。)
It's also reentrant; strtok
isn't. (BTW: reentrant has nothing to do with multi-threading. strtok
breaks already with nested loops. One can use strtok_r
but it's not as portable.)
这篇关于从strtok在一个字符串解析空标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!