Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare words in two strings

Tags:

c

string

I have made two strings. User can fill them both.

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

I need to find similar words from both strings. For example,

Text= I am here for all my life

Text2= They are here to win us all

I need to program finds similar words like 'here','all'. I tried like this but it don't found all words.

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

and then printf but i think it isnt the right thing.

like image 973
Einārs Ozols Avatar asked Mar 23 '23 00:03

Einārs Ozols


1 Answers

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, " ");
}
like image 150
Filipe Gonçalves Avatar answered Mar 31 '23 21:03

Filipe Gonçalves