c - C 中 strtok 的奇怪行为?

标签 c string strtok

我正在编写一个程序,我想在其中打印两个字符串之间的常用单词。好吧,我使用两个循环并将这些字符串拆分在这两个循环中。但没有得到应有的结果。然后我稍微改变了程序,然后我研究了外循环只运行一次。不明白为什么?有人有什么想法吗?

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
    char str1[] = "Japan Korea Spain Germany Australia France ";
    char str2[] = "England USA Russia Italy Australia India Nepal France";
    char *tar1 = strtok(str1," ");
    char *tar2 = NULL;
    while(tar1)
    {
       tar2 = strtok(str2," ");
       while(tar2)
       {
          if(strcmp(tar1,tar2)) printf("%s %s\n",tar1 , tar2);
          tar2 = strtok(NULL," ");
       }
       tar1 = strtok(NULL," ");
       tar2 = NULL;
    } 
    return 0;
}

最佳答案

您不能同时对两个不同的字符串使用 strtok,也不能多次解析一个字符串,因为 strtok 已经通过破坏字符串来修改该字符串带有 nul 终止符。

此示例在检查匹配之前,将 token 指针提取到每个输入字符串的指针数组中。

#include <stdio.h>
#include <string.h>

#define MAXSTR 20
int main()
{
    char str1[] = "Japan Korea Spain Germany Australia France ";
    char str2[] = "England USA Russia Italy Australia India Nepal France";
    char *tar1[MAXSTR];
    char *tar2[MAXSTR];
    char *tok;
    int ind1 = 0, ind2 = 0;
    int i, j;

    tok = strtok(str1, " \t");
    while(tok != NULL && ind1 < MAXSTR) {
        tar1[ind1++] = tok;
        tok = strtok(NULL, " \t");
    }

    tok = strtok(str2, " \t");
    while(tok != NULL && ind2 < MAXSTR) {
        tar2[ind2++] = tok;
        tok = strtok(NULL, " \t");
    }

    for(i=0; i<ind1; i++) {
        for(j=0; j<ind2; j++) {
            if(strcmp(tar1[i], tar2[j]) == 0) {
                printf("%s\n", tar1[i]);
                break;
            }
        }
    }
    return 0;
}

程序输出:

Australia
France

关于c - C 中 strtok 的奇怪行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37046064/

相关文章:

c++ - 有没有办法让 C++ 从 cin 中接收未定义数量的字符串?

c - 在 C 中处理文本文件的异常行为

线程可以有多个参数吗?

c - 头文件中的变量可共享给多个 .c 文件

python - 类型错误 : split() takes no keyword arguments in Python 2. x

c - 如何分离特定数据

c - atoi() 返回奇怪的值

c - 绕过 "cast increases required alignment order"消息

c - 为什么跟踪器服务器不理解我的请求? (比特流协议(protocol))

java - 从 xml 字符串构建 DOM 文档给我一个空文档