简体   繁体   中英

Compare part of an input string using strcmp() in C

Normally strcmp is used with two arguments [eg strcmp(str1,"garden")], and it will return 0 if both are the same.

Is it possible to compare part of the input, say the first five character of the input? (for example, strcmp(str1,"garde",5) )

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

int main(void) {

    char str1[] = "garden";

    if (strcmp(str1, "garden") == 0)
    {
        printf("1");
    }
    if (strcmp(str1, "garden", 6) == 0)
    {
        printf("2");
    }
    if (strcmp(str1, "garde", 5) == 0)
    {
        printf("3");
    }
    return 0;
}

Use strncmp:

if (strncmp(str, "test", 4) == 0) { printf("it matches!"); }

See http://www.cplusplus.com/reference/cstring/strncmp/ for more info.

You're looking for strncmp() .

Keep in mind that C does not supports overloading, so each "variation" of the same function has an unique name.

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