在 C 中使用 strtok 比较单词

Compare words using strtok in C

我开始学习c了。目前,我正在尝试从两个字符数组中获取单词,以便我可以使用名为 compare 的辅助方法来比较它们。但是,我的 strtok() 给了我奇怪的输出。 这是我的代码:

char *headerPointer=headers;
    char *linePointer=firstline;
    printf("Header-%s\n",headers);
    printf("Line-%s\n",firstline);
    headerPointer=strtok(headerPointer,",");
    linePointer=strtok(linePointer,",");
    while ((headerPointer!=NULL&&linePointer!=NULL)) {
            printf("\nPrinting words from headers\n");
            printf("%s",headerPointer);
            headerPointer=strtok(NULL,",");
            printf("\nPrinting words from line\n");
            printf("%s",linePointer);
            linePointer=strtok(NULL, ",");

        }

以上代码产生的输出:

Header-Hello,My,name,is,Ram.
Line-I,own,20,thousand,bucks.

Printing words from headers-
Hello.
Printing words from line-
I.
Printing words from headers-
own.
Printing words from line-
20.
Printing words from headers-
thousand.
Printing words from line-
bucks.

我不明白为什么 header 从 line 打印内容,my,name,is,ram 到哪里去了?

我尝试使用以下代码编写它们,并且同样的代码产生了所需的输出。 不同的代码风格:

char *headerPointer=headers;
    char *linePointer=firstline;
    printf("Header%s\n",headers);
    printf("Line%s\n",firstline);
    headerPointer=strtok(headerPointer,",");

        while(headerPointer!=NULL)
    {
        printf("\nPrinting words from headers\n");
        printf("%s",headerPointer);
        headerPointer=strtok(NULL,",");

    }
    linePointer=strtok(linePointer,",");

    while(linePointer!=NULL){
        printf("\nPrinting words from line\n");
        printf("%s",linePointer);
        linePointer=strtok(NULL, ",");
    }

输出:

Header-Hello,My,name,is,Ram.
Line-I,own,20,thousand,bucks.

Printing words from headers-
Hello.
Printing words from headers-
My.
Printing words from headers-
name.
Printing words from headers-
is.
Printing words from headers-
Ram.
Printing words from line-
I.
Printing words from line-
own.
Printing words from line-
20.
Printing words from line-
thousand.
Printing words from line-
bucks.

请解释为什么基于相同想法的两个代码会产生不同的结果?我们可以修改第一个代码来给出第二个结果吗?我尝试搜索并遵循已经可用的解决方案,但没能走多远。

strtok 是有状态且不可重入的;它一次只能标记一个字符串。在您的原始代码中,您试图同时对两个输入进行标记化,但它不能这样做;它只是根据提供的最后一个非 NULL 字符串参数进行标记化,即 linePointer.

要完成这项工作,您需要使用 strtok_r,它允许您保存每个字符串的进度,而不会覆盖另一个字符串的进度。