#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變量的值了!
這個靜態變量的作用,就是記錄原始字符串的長度的!