这是我的部分代码:
int main ()
{
char *sentence;
char *token;
int counter = 1;
sentence = (char*)malloc(255*sizeof(char));
scanf("%[^\n]s", sentence);
token = strtok(sentence, " ");
char *temp;
while(token != NULL)
{
printf("Token %d: %s\n", counter, token);
token = strtok(NULL, " ");
//temp = token;
//temp = strtok(NULL, " ");
counter++;
}
return 0;
}
如果我在输入“why herrow there”时运行它,它会给我:
Token 1: why
Token 2: herrow
Token 3: there
如果我取消注释 temp 那么它只会给我:
Token1: why
Token 2: herrow
即使我认为我没有用 temp 阻碍我的代币值(value),它仍然会影响我的代币值(value)。我不希望 temp 对我的原始 token 有任何影响。我该怎么做?
最佳答案
你的字符串有三个词 "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
While 循环中断!
那么它只打印:
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);
关于c - 如何在不更改初始 token 的情况下存储 strtok 的临时值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19074456/