我已经创建了两个字符串。用户可以填写它们。
char text[200];
char text2[200];
我需要从这两个字符串中找到相似的单词。例如,
Text= 我一生都在这里
Text2= 他们在这里赢得我们所有人
我需要编写程序来查找相似的单词,如“这里”、“所有”。我尝试过下面这样,但并没有找到所有单词。
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 <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, " ");
}
strtok()
和 strstr()
的组合。strtok()
将 text
拆分为标记,并使用 strstr()
在 text2
中查找该标记。strtok_r()
替代 strtok()
。text
分解为单词,并使用strstr
在text2
中搜索这些单词。
strstr
是做什么的吗? - digital_revenantstrstr
的man页面以了解为什么你尝试的方法不起作用。在text
中不会出现text2
的[完整]内容。 - Mike