C:用 strtok 从字符串中解析空标记 [英] C: 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, "|");
}
有什么建议吗?
推荐答案
在那种情况下,我通常更喜欢 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.)
这篇关于C:用 strtok 从字符串中解析空标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!