14.2. strcmp(), strncmp()

Compare two strings and return a difference.


#include <string.h>

int strcmp(const char *s1, const char *s2);
int strncmp(const char *s1, const char *s2, size_t n);


Both these functions compare two strings. strcmp() compares the entire string down to the end, while strncmp() only compares the first n characters of the strings.

It's a little funky what they return. Basically it's a difference of the strings, so if the strings are the same, it'll return zero (since the difference is zero). It'll return non-zero if the strings differ; basically it will find the first mismatched character and return less-than zero if that character in s1 is less than the corresponding character in s2. It'll return greater-than zero if that character in s1 is greater than that in s2.

For the most part, people just check to see if the return value is zero or not, because, more often than not, people are only curious if strings are the same.

These functions can be used as comparison functions for qsort() if you have an array of char*s you want to sort.

Return Value

Returns zero if the strings are the same, less-than zero if the first different character in s1 is less than that in s2, or greater-than zero if the first difference character in s1 is greater than than in s2.


char *s1 = "Muffin";
char *s2 = "Muffin Sandwich";
char *s3 = "Muffin";

strcmp("Biscuits", "Kittens"); // returns < 0 since 'B' < 'K'
strcmp("Kittens", "Biscuits"); // returns > 0 since 'K' > 'B'

if (strcmp(s1, s2) == 0)
    printf("This won't get printed because the strings differ");

if (strcmp(s1, s3) == 0)
    printf("This will print because s1 and s3 are the same");

// this is a little weird...but if the strings are the same, it'll
// return zero, which can also be thought of as "false".  Not-false
// is "true", so (!strcmp()) will be true if the strings are the
// same.  yes, it's odd, but you see this all the time in the wild
// so you might as well get used to it:

if (!strcmp(s1, s3))
    printf("The strings are the same!")

if (!strncmp(s1, s2, 6))
    printf("The first 6 characters of s1 and s2 are the same");

See Also

memcmp(), qsort()