文字列には 3 つの単語があります。ステートメント"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 ループの 2 回目の反復:
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++;
}
3 番目の反復トークンが 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);
コード作業。