示例代码:
#include <stdio.h>
#include <string.h>
int main()
{
char str[1024];
char *buff, *temp, *result = NULL;
char tok[] = " ";
printf("enter string:\n");
gets(str);
buff = str;
result = strtok(buff, tok);
while (result != NULL)
{
printf("%s\n", result);
result = strtok(NULL, tok);
}
printf("\n");
char tok1[] = " ";
temp = str;
result = strtok(temp, tok1);
while (result != NULL)
{
printf("%s\n", result);
result = strtok(NULL, tok1);
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码给出以下输出:
enter string:
Hello how are you
Hello
how
are
you
Hello
Run Code Online (Sandbox Code Playgroud)
但是,我希望输出是:
enter string:
Hello how are you
Hello
how
are
you
Hello
how
are
you
Run Code Online (Sandbox Code Playgroud)
为什么 strtokNULL在打印第一个单词(即“hello”)后返回?我正在使用另一个变量并初始化它并使用另一个令牌变量。我怎样才能得到想要的结果?
strtok()修改输入字符串。因此,在第一轮标记化之后,原始字符串str已被修改(sincetemp指向str)。
因此,在将字符串传递给之前先获取该字符串的副本strtok()。
其他改进:
1) 不要使用gets()已被弃用的。使用fgets()替代方法可以避免潜在的缓冲区溢出。
2)使用strtok_r()它,因为它是可重入的。