简体   繁体   中英

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?

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.

if (strcmp((a + index), b) == 0) { ... }

strcmp takes two pointers, so you add the index directly.

However, you should add a terminating NULL byte to each string.

Assuming those are actually strings rather than character arrays with no string terminator, this is quite easy to do.

You sate you no the index of the w in world so it's a matter of:

strcmp (b, a+index)

or:

strcmp (b, &(a[index]))

depending on which you think reads better (the underlying code should be pretty much the same).

See, for example, this program:

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

int main (void) {
    char *str1 = "world";
    char *str2 = "hello world";

    for (size_t i = 0; i < strlen (str2); i++)
        printf ("%s on match '%s' with '%s'\n",
            strcmp (str1, str2+i) ? "No " : "Yes",
            str1, str2+i);

    return 0;
}

which outputs:

No  on match 'world' with 'hello world'
No  on match 'world' with 'ello world'
No  on match 'world' with 'llo world'
No  on match 'world' with 'lo world'
No  on match 'world' with 'o world'
No  on match 'world' with ' world'
Yes on match 'world' with 'world'
No  on match 'world' with 'orld'
No  on match 'world' with 'rld'
No  on match 'world' with 'ld'
No  on match 'world' with 'd'

Whether they're string literals or properly terminated character arrays will make no difference. Replacing the two declaration lines with:

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

will work equally well.

If they're not properly terminated, the str... calls are not really the right ones to use.

if (strcmp(&a[6],b) == 0)

希望这可以帮助

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM