15

Normally strcmp is used with two arguments [e.g. 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;
}
1

2 Answers 2

19

Use strncmp:

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

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

Sign up to request clarification or add additional context in comments.

1 Comment

Hey Troy thanks for replying. Does it works with 3 arguments cuz I get this error, prog.c:10:29: error: macro "strcmp" passed 3 arguments, but takes just 2
3

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.

1 Comment

Hey Crozin, thanks. Which answer should I approve since both of you answer at about the same time lol...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.