比较两个字符串中的单词

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

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

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

文字=我一辈子都在这里

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

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

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

然后printf,但我认为这是不对的。

我想这就是你想要的:

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

您需要使用strtok()strstr()

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

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

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

可能的算法实现:

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

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

有两个线程我觉得对你有帮助。

如何在C中有效地从句子中提取单词?

C中每个空格分割字符串。

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