我想这就是你想要的:
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, " ");
}
It uses strtok()
逐字阅读句子,并且strstr()
在另一个句子中搜索相应的单词。请注意,这不是很有效,如果您有大量数据,则必须考虑更智能的算法。
UPDATE:
由于您不想匹配嵌入的单词,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, " ");
}