Search code examples
carraysstringstrcmp

Using strcmp on a subset of a string


I want to use strcmp to compare the subset of a string with another string.

Say I have:

a[] = {'h','e','l','l','o',' ','w','o','r','l',d'};

and

b[] = {'w','o','r','l','d};

I want to compare the second word of a with the entire string b. I know the starting index of the second word in a. Is there a way to do this directly using strcmp or does more word on a need to be done first?


Solution

  • a and b are char arrays, but they are not strings, because they are not null-terminated.

    If they were modified to null-terminated like this:

    char a[] = {'h','e','l','l','o',' ','w','o','r','l','d', '\0'};
    
    char b[] = {'w','o','r','l','d', '\0'};
    

    And the index of the second word of a is known like you said, then yes, you can use strcmp(a + 6, b) to compare.