c - 使用 strtok 比较 strtok 函数嵌套结果中的两个单词的问题

标签 c

我正在寻找将数组中的单词与另一个数组中的字典中的单词进行比较,以查找找到的最大单词数

我使用了 strtok,因为两者中的单词都是用空格分隔的,但它不起作用。我需要你的帮助,请

 void chercherScoreMotDansDico(char msgBootforce [], int* 
 maxCorrepondance, char* mot, char* dicoActuel, char* 
 bonResultatBootforce) {
     int i = 0;
     char* motdico = NULL;
     char tmpMsgBootForce [3000] = {0};

     strcpy(tmpMsgBootForce, msgBootforce);

     mot = strtok (tmpMsgBootForce, " ");

     while (mot != NULL) {
          motdico = strtok (dicoActuel, " ");

          while (motdico != NULL) {
              if (strcmp(mot,motdico) == 0)   ++i;
              motdico = strtok (NULL, " ");
          }

          mot = strtok (NULL," ");  
    }

    if (i > *(maxCorrepondance)) {
        *(maxCorrepondance) = i;
        strcat(bonResultatBootforce, msgBootforce);
    }   
 }

最佳答案

不能同时对两个不同的字符串使用 strtok() 。; strtok() 有一个内部指针,用于存储当前正在处理的字符串的地址。如果您使用字符串调用 strtok() ,然后使用不同的字符串调用 strtok() ,那么当您执行 strtok(NULL, delim) 时它将继续指定的最后一个字符串。

参见https://en.cppreference.com/w/c/string/byte/strtok

This function is destructive: it writes the '\0' characters in the elements of the string str. In particular, a string literal cannot be used as the first argument of strtok. Each call to strtok modifies a static variable: is not thread safe. Unlike most other tokenizers, the delimiters in strtok can be different for each subsequent token, and can even depend on the contents of the previous tokens. The strtok_s function differs from the POSIX strtok_r function by guarding against storing outside of the string being tokenized, and by checking runtime constraints.

有一个新版本的 strtok() 函数 strtok_s(),它有一个额外的地址参数,供指针变量使用,而不是内部指针strtok() 使用的变量。

关于c - 使用 strtok 比较 strtok 函数嵌套结果中的两个单词的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57049672/

相关文章:

C memcpy() 一个函数

c - int main() { }(没有 "void")在 ISO C 中有效且可移植吗?

c - 在 C 中使用通配符查找文件名

c - 允许在信任边界进行冗余空指针检查

c - 将一串输入存储到 C 中的结构中

c - 不理解自定义 C shell 的逻辑

Python C 模块 - Malloc 在特定版本的 Python 中失败

c - 多次调用 Getenv() 时出错

c - 使用 Pure C 显示 PGM 图像 (p5) 的直方图像素值,无需任何图像处理库

c - 按位运算符比较错误