比较两个字符串中的单词

Ein*_*ols 4 c string

我做了两个字符串.用户可以填写它们.

char text[200];
char text2[200];  
Run Code Online (Sandbox Code Playgroud)

我需要从两个字符串中找到类似的单词.例如,

文字=我一生都在这里

Text2 =他们在这里赢得了我们所有人

我需要编程找到类似'here','all'之类的单词.我试过这样但却找不到所有的话.

if(strstr(text,text2) != NULL)
Run Code Online (Sandbox Code Playgroud)

然后是printf,但我觉得这不对.

Fil*_*ves 5

我想这就是你想要的:

char text[] = "I am here for all my life";
char text2[] = "They are here to win us all";

char *word = strtok(text, " ");

while (word != NULL) {
    if (strstr(text2, word)) {
        /* Match found */
        printf("Match: %s\n", word);
    }
    word = strtok(NULL, " ");
}
Run Code Online (Sandbox Code Playgroud)

它用于strtok()逐字阅读句子,并strstr()在另一句话中搜索相应的单词.请注意,这不是很有效,如果您有大量数据,则必须考虑使用更智能的算法.

更新:

由于您不想匹配嵌入的单词,strstr()对您没有多大帮助.而不是使用strstr(),你必须使用自定义功能.像这样的东西:

#include <ctype.h>
int searchword(char *text, char *word) {
    int i;

    while (*text != '\0') {
        while (isspace((unsigned char) *text))
            text++;
        for (i = 0; *text == word[i] && *text != '\0'; text++, i++);
        if ((isspace((unsigned char) *text) || *text == '\0') && word[i] == '\0')
            return 1;
        while (!isspace((unsigned char) *text) && *text != '\0')
            text++;
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

其他代码保持不变,但strstr()通过调用此新函数替换调用:

char text[] = "I am here for all my life";
char text2[] = "They are here to win us all";

char *word = strtok(text, " ");

while (word != NULL) {
    if (searchword(text2, word)) {
        /* Match found */
        printf("Match: %s\n", word);
    }
    word = strtok(NULL, " ");
}
Run Code Online (Sandbox Code Playgroud)