C语言 Strtok 分隔所有空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19803437/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Strtok to separate all whitespace
提问by Haskell
I'm trying to split a string at spaces and tabs.
我正在尝试在空格和制表符处拆分字符串。
char * token = strtok(input, " \t");
works only for spaces. What am I doing wrong?
仅适用于空间。我究竟做错了什么?
回答by Mark Hendrickson
Here is an example that illustrates that strtok() will work on tabs or spaces. The key is to pass in NULL on the all but the first call to strtok().
这是一个示例,说明 strtok() 将在制表符或空格上工作。关键是在除第一次调用 strtok() 之外的所有函数中传入 NULL。
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
char buffer[1024];
int rv = sprintf(buffer, "a string\ttokenize.");
char *token = strtok(buffer, " \t");
int i = 0;
printf("cnt token\n");
printf("==========\n");
while (token) {
printf("%2d %s\n", i++, token);
token = strtok(NULL, " \t");
}
return 0;
}
output from above program is as follows below.
上述程序的输出如下。
cnt token
==========
0 a
1 string
2 tokenize.

