Search code examples
cstringcomparewords

finding the same words in two strings in c


#include <stdio.h>
#include <string.h>

int main(int argc, char* argv[])
    {
    char* firstString = argv[1];
    char* secondString = argv[2];
    int i, j;
    int flag = 0;
    for (i=0; i<strlen(firstString); i++)
    {
        for (j=0; j<strlen(secondString); j++)
        {
            if (firstString[i] == secondString[j])
            {
                flag = 1;   
            }
            else
            {
                flag = 0;
                break;
            }
        }
    }
    if (flag == 1)
    {
        printf ("true\n");
        return 0;
    }
    else
    {
        printf ("false\n");
    }
    return 1;
}

So the program I need to write is to compare 2 text strings, and if the same words in the second string appears in the first string, then i print true, otherwise, I print false.

So for example, "I hate you" "hate" --- this would print true "I hate you" "I am a walrus" --- this would print false

But for some reason, this code just keeps print false and I dunno what's wrong with it. Would anyone be able to help me?

Thanks!


Solution

  • you can try as :

    int main(int argc, char* argv[])
    {
        char* firstString = argv[1];
        char* secondString = argv[2];
        int flag = 0;
        int count=0;
    
        int len2=strlen(secondString);
       while(*firstString!=NULL)
       {
          while((*firstString==*secondString)&&(*secondString!='\0')){
              firstString++;
              secondString++;                             
              count++;                            
          }
        firstString++;
        if(count==len2){
         flag=1;
         break;
        }
        else
         flag=0;
    
     }   
    
    
        if (flag == 1)
        {
            printf ("true\n");
    
        }
        else
        {
            printf ("false\n");
        }
    
        return 0;
    }