【问题标题】:Compare words in two strings比较两个字符串中的单词
【发布时间】:2013-10-15 17:49:50
【问题描述】:

我做了两个字符串。用户可以同时填写。

char text[200];
char text2[200];  

我需要从两个字符串中找到相似的词。例如,

Text=我一生都在这里

Text2= 他们是来赢得我们所有人的

我需要通过程序找到类似的词,例如“这里”、“全部”。 我试过这样,但没有找到所有单词。

if(strstr(text,text2) != NULL)

然后 printf 但我认为这不是正确的事情。

【问题讨论】:

  • 你知道strstr是做什么的吗?
  • 这个问题的答案不是函数调用,而是你必须实现的算法。因此,请继续努力:思考问题并设计解决方案。
  • 如果只有一个函数可以做到这一点,那么它很可能不会作为项目/家庭作业/无论它是什么分配给你。查看man pagestrstr 以了解为什么您尝试的方法不起作用。 text2的[完整]内容不会出现在text

标签: c string


【解决方案1】:

我想这就是你想要的:

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, " ");
}

它使用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;
}

其他代码保持不变,但将对 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, " ");
}

【讨论】:

  • 它有效,但是如果 text[]="Dog in the house" text2[]="indoor Skatepark" 那么匹配将是 'in'
  • 嗯,我以为你想要那个。您必须编写自己的 strstr() 版本来解决此问题。我会在几分钟内更新我的答案并提供解决方法。
  • @user2883601 我用解决方法更新了我的帖子。在这里测试,似乎可以工作,如果现在还可以,请告诉我。
【解决方案2】:

您需要使用strtok()strstr() 的组合。

text 拆分为带有strtok() 的标记,并使用strstr()text2 中搜索该标记

为了安全而不是strtok()你也可以使用strtok_r()

【讨论】:

    【解决方案3】:

    text 分解为单词并使用strstrtext2 中搜索这些单词

    【讨论】:

      【解决方案4】:

      可能的算法实现:

      • 从用户那里获取两个字符串(使用char ** 而不是char * 可能会更好)
      • 使用qsort对每个字符串进行排序
      • 从最小的字符串列表的开头开始搜索

      注意:可以在O(n)时间执行最后一步

      【讨论】:

        【解决方案5】:

        我认为有两个主题对你有帮助。

        How to extract words from a sentence efficiently in C?

        Split string in C every white space.

        使用strtok 和空格作为分隔符似乎是将两个字符串解析为单词的一种合适的解决方案。听起来您已经有效地实施了第二步(strsrt)。

        【讨论】:

          猜你喜欢
          • 2019-04-27
          • 1970-01-01
          • 1970-01-01
          • 2021-05-09
          • 2016-06-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多