同时标记多个字符串 [英] Tokenizing multiple strings simultaneously
问题描述
假设我有三个 c 风格的字符串,char buf_1[1024]
、char buf_2[1024]
和 char buf_3[1024]
>.我想标记它们,并使用所有三个中的第一个标记执行操作,然后使用所有三个中的第二个标记执行相同操作,等等.显然,我可以调用 strtok
并从每次我想要一个新令牌时开始.或者,对所有令牌进行预处理,将它们放入三个数组中,然后从那里开始,但如果有的话,我想要一个更简洁的解决方案.
Say I have three c-style strings, char buf_1[1024]
, char buf_2[1024]
, and char buf_3[1024]
. I want to tokenize them, and do things with the first token from all three, then do the same with the second token from all three, etc. Obviously, I could call strtok
and loop through them from the beginning each time I want a new token. Or alternatively, pre-process all the tokens, stick them into three arrays and go from there, but I'd like a cleaner solution, if there is one.
推荐答案
听起来您想要 strtok
的可重入版本,strtok_r
它使用第三个参数来保存它在字符串中的位置,而不是函数中的静态变量.
It sounds like you want the reentrant version of strtok
, strtok_r
which uses a third parameter to save its position in the string instead of a static variable in the function.
这是一些示例骨架代码:
Here's some example skeleton code:
char buf_1[1024], buf_2[1024], buf_3[1024];
char *save_ptr1, *save_ptr2, *save_ptr3;
char *token1, *token2, *token3;
// Populate buf_1, buf_2, and buf_3
// get the initial tokens
token1 = strtok_r(buf_1, " ", &save_ptr1);
token2 = strtok_r(buf_2, " ", &save_ptr2);
token3 = strtok_r(buf_3, " ", &save_ptr3);
while(token1 && token2 && token3) {
// do stuff with tokens
// get next tokens
token1 = strtok_r(NULL, " ", &save_ptr1);
token2 = strtok_r(NULL, " ", &save_ptr2);
token3 = strtok_r(NULL, " ", &save_ptr3);
}
这篇关于同时标记多个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!