#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.
第二次參數(shù)竟然可以NULL
是因為strtok中用static指針記住了上次處理后的位置
我想是因為這個函數(shù)內(nèi)部實現(xiàn)時,用到了靜態(tài)變量,而要不要修改這個變量,就是要根據(jù)第一個參數(shù)來確定!
當(dāng)為NULL時,就不再修改Static變量的值了!
這個靜態(tài)變量的作用,就是記錄原始字符串的長度的!