c - 如何在不更改初始 token 的情况下存储 strtok 的临时值

标签 c pointers token strtok temp

这是我的部分代码:

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);

Code working .

关于c - 如何在不更改初始 token 的情况下存储 strtok 的临时值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19074456/

相关文章:

java - 如何从 JNA 调用 ALSA 分配#define?

c - 有没有办法使用静态代码分析器显示函数的所有可能的回溯?

c - 将结构指针分配给双指针结构

php - Outlook 链接预览中断 "one time URL"

javascript - JWT:在多域级别处理 token 身份验证

c - 从 C 中的 ELF 部分中提取字符串

iphone - 使用相同的指针指向不同的UIViewController

C 指针和访问数组

c - 不在 if 语句之外打印

security - 安全 token URL - 它有多安全?代理身份验证作为替代方案?