【发布时间】:2015-11-16 03:33:26
【问题描述】:
我在http://www.cplusplus.com/reference/cstring/strtok/ 上找到了使用 strtok() 的示例,但不明白它们是如何通过 "pch = strtok (NULL, " ,.-");" 从一个令牌到另一个令牌获取的
代码如下:
/* strtok example */
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] ="- This, a sample string.";
char * pch;
printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str," ,.-");
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, " ,.-");
}
return 0;
}
这是输出:
Splitting string "- This, a sample string." into tokens:
This
a
sample
string
【问题讨论】:
-
阅读the manual。它非常明确地解释了这一点。如果看完后你还是不明白,请具体说明你不明白的地方。
-
不要在库代码中使用
strtok()。如果您需要标记化,请考虑 Unix 上的strtok_r()和 Windows 上的strtok_s()。或者使用其他技术来标记您的数据。strcspn()、strspn()和strpbrk()等函数随处可用(它们是 C89/C90 标准的一部分),并且非常有用。