您的字符串有三个单词"why herrow there"
添加temp
语句时的情况:
第一步:
token = strtok(sentence, " "); <-- sentence: `"why\0herrow there"`
// token = sentence
char *temp;
第一次迭代:
while(token != NULL) // token is not null <-------------------------------+
{ |
printf("Token %d: %s\n", counter, token); // first time print why |
|
token = strtok(NULL, " "); <-- sentence: `"why\0herrow\0there"` |//step-2
<-- token points to "herrow" substring (*)|
temp = token; <---temp = token |
temp = strtok(NULL, " "); <---sentence: `"why\0herrow\0there"` |//step-3
<-- temp = "there" sub string |//Last token
counter++; |-------------------------------+
}
while循环的第二次迭代:
while(token != NULL) // token is not null, it is pointing to sustring "herrow"
{
printf("Token %d: %s\n", counter, token); printing "herrow"
token = strtok(NULL, " "); <-- no next token, token becomes NULL //step-4
temp = token;
temp = strtok(NULL, " "); <-- no next token, so temp becomes NULL //step-5
counter++;
}
第三次迭代令牌为 NULL
虽然循环中断!
所以它只打印:
Token1: why
Token 2: herrow
根据评论!
token = strtok(sentence, " "); // first token
next_token = token;
while(next_token != NULL){
printf("Token %d: %s\n", counter, token);
if(next_token = strtok(NULL, " "))
token = next_token; //Last token in string
// here you have last token that is not NULL
counter++;
}
// next_token is NULL, but token is not NULL it is equals to last token in string
counter--;
printf("Token %d: %s\n", counter, token);
代码工作。