在C中嵌套strtok函数问题
我有这样的string:
a;b;c;d;e f;g;h;i;j 1;2;3;4;5
我想分析它的元素。 我使用嵌套的strtok函数,但它只是分割第一行,并使空指令指针。 我怎么能克服这个? 这里是代码:
token = strtok(str, "\n"); while(token != NULL && *token != EOF) { char a[128], b[128]; strcpy(a,token); strcpy(b,a); printf("a:%s\n",a); char *token2 = strtok(a,";"); while(token2 != NULL) { printf("token2 %s\n",token2); token2 = strtok(NULL,";"); } strcpy(token,b); token = strtok(NULL, "\n"); if(token == NULL) { printf("its null"); } }
输出:
token 2 a token 2 b token 2 c token 2 d token 2 e
你不能用strtok()
; 如果可用,请使用POSIX的strtok_s()
或Microsoft的strtok_s()
,或者重新考虑您的devise。
char *strtok_r(char *restrict s, const char *restrict sep, char **restrict lasts); char *strtok_s(char *strToken, const char *strDelimit, char **context);
这两个function是可以互换的。 尽pipestrtok_s()
是C11(ISO / IEC 9899:2011中附录K strtok_s()
的可选部分,但微软以外的供应商很less实现该部分中的接口。
用strtok_r()
#include <string.h> #include <stdio.h> int main(void) { char str[] = "a;b;c;d;e\nf;g;h;i;j\n1;2;3;4;5\n"; char *end_str; char *token = strtok_r(str, "\n", &end_str); while (token != NULL) { char *end_token; printf("a = %s\n", token); char *token2 = strtok_r(token, ";", &end_token); while (token2 != NULL) { printf("b = %s\n", token2); token2 = strtok_r(NULL, ";", &end_token); } token = strtok_r(NULL, "\n", &end_str); } return 0; }
结果
a = a;b;c;d;e b = a b = b b = c b = d b = e a = f;g;h;i;j b = f b = g b = h b = i b = j a = 1;2;3;4;5 b = 1 b = 2 b = 3 b = 4 b = 5
没有strtok_r()
这在上下文中工作 – 只要数据以换行符结束。
#include <string.h> #include <stdio.h> int main(void) { char data[] = "a;b;c;d;e\nf;g;h;i;j\n1;2;3;4;5\n"; char *string = data; char *token = strchr(string, '\n'); while (token != NULL) { /* String to scan is in string..token */ *token++ = '\0'; printf("a = %s\n", string); char *token2 = strtok(string, ";"); while (token2 != NULL) { printf("b = %s\n", token2); token2 = strtok(NULL, ";"); } string = token; token = strchr(string, '\n'); } return 0; }
产量
a = a;b;c;d;e b = a b = b b = c b = d b = e a = f;g;h;i;j b = f b = g b = h b = i b = j a = 1;2;3;4;5 b = 1 b = 2 b = 3 b = 4 b = 5
strtok_r
是最好也是最安全的解决scheme,但是也有一种方法可以用strtok
来实现:
#include <string.h> #include <stdio.h> int main () { char str[] = "a;b;c;d;e\nf;g;h;i;j\n1;2;3;4;5\n"; char *line; char *token; char buf[256]; for (line = strtok (str, "\n"); line != NULL; line = strtok (line + strlen (line) + 1, "\n")) { strncpy (buf, line, sizeof (buf)); printf ("Line: %s\n", buf); for (token = strtok (buf, ";"); token != NULL; token = strtok (token + strlen (token) + 1, ";")) { printf ("\tToken: %s\n", token); } } return 0; }
输出:
Line: a;b;c;d;e Token: a Token: b Token: c Token: d Token: e Line: f;g;h;i;j Token: f Token: g Token: h Token: i Token: j Line: 1;2;3;4;5 Token: 1 Token: 2 Token: 3 Token: 4 Token: 5