/* 先分隔句子 */ pSentence = strtok(szTest, ";"); while (NULL != pSentence) { printf("The sentence is %s.\n", pSentence);
/* 再分隔单词 */ pWord = strtok(pSentence, " "); while (NULL != pWord) { printf("The word is %s.\n", pWord); pWord = strtok(NULL, " "); }
pSentence = strtok(NULL, ";"); }
return0; }
预期结果如下:
1 2 3 4 5 6 7 8 9
$ gcc test_strtok.c $ ./a.out The sentence is Hello world. The word is Hello. The word is world. The sentence is I'm Pele. The word is I'm. The word is Pele. $
可实际结果如下:
1 2 3 4 5 6
$ gcc test_strtok.c $ ./a.out The sentence is Hello world. The word is Hello. The word is world. $
/* Parse S into tokens separated by characters in DELIM. If S is NULL, the last string strtok() was called with is used. For example: char s[] = "-abc-=-def"; x = strtok(s, "-"); // x = "abc" x = strtok(NULL, "-="); // x = "def" x = strtok(NULL, "="); // x = NULL // s = "abc\0=-def\0" */ char * STRTOK(char *s, constchar *delim) { char *token;
if (s == NULL) s = olds;
/* 跳过了字符串前面的分隔符,如果字符串只剩下尾部的分隔符,跳过前导符相当于忽略尾部的分隔符--TOP4坑 */ /* Scan leading delimiters. */ s += strspn (s, delim); if (*s == '\0') { olds = s; returnNULL; }
/* Find the end of the token. */ token = s; s = strpbrk (token, delim); if (s == NULL) /* This token finishes the string. */ olds = __rawmemchr (token, '\0'); else/* 找到一个分隔符就返回,下次进入该函数会跳过前导分隔符,此为TOP3坑 */ { /* Terminate the token and make OLDS point past it. */ *s = '\0'; /* 将分隔符所在位置置0,此为TOP2坑 */ olds = s + 1; } return token; }