I think this is what you want:
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()
to read the sentence word by word, and strstr()
to search for the corresponding word in the other sentence. Note that this is not very efficient, if you have big chunks of data you'll have to consider a smarter algorithm.
UPDATE:
Since you don't want to match embedded words, strstr()
is not of much help for you. Instead of using strstr()
, you have to use a custom function. Something like this:
#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;
}
The other code stays the same, but replace the call to strstr()
by a call to this new function:
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, " ");
}