我想这就是你想要的:
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, " ");
}