#include <string.h>
#include <stdio.h>
int main(void)
{
char input[16] = "abc,dhh,eee";
char *p;
/* strtok places a NULL terminator
in front of the token, if found */
p = strtok(input, ",");
if (p) printf("%s\n", p);
/* A second call to strtok using a NULL
as the first parameter returns a pointer
to the character following the token */
p = strtok(NULL, ",");
if (p) printf("%s\n", p);
p = strtok(NULL, ",");
if (p) printf("%s\n", p);
return 0;
}
MSDN上的原话:
On the first call to strtok, the function skips leading delimiters and returns a pointer to the first token in strToken, terminating the token with a null character. More tokens can be broken out of the remainder of strToken by a series of calls to strtok. Each call to strtok modifies strToken by inserting a null character after the token returned by that call. To read the next token from strToken, call strtok with a NULL value for the strToken argument. The NULL strToken argument causes strtok to search for the next token in the modified strToken. The strDelimit argument can take any value from one call to the next so that the set of delimiters may vary.
第二次参数竟然可以NULL
是因为strtok中用static指针记住了上次处理后的位置
我想是因为这个函数内部实现时,用到了静态变量,而要不要修改这个变量,就是要根据第一个参数来确定!
当为NULL时,就不再修改Static变量的值了!
这个静态变量的作用,就是记录原始字符串的长度的!