cs24-23fa strcmp

Introduction to Computing Systems (Fall 2023)

Name

strcmp - compare two strings

Synopsis

#include <string.h>

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

Description

The strcmp() function compares the two strings s1 and s2. It returns an integer less than, equal to, or greater than zero if s1 is found, respectively, to be less than, to match, or be greater than s2.

The strncmp() is similar, except that it compares only the first (at most) n bytes of s1 and s2.

Example

#include <assert.h>
#include <string.h>

int main() {
    char s1[11] = "greetings!";
    char s2[7] = "hello!";
    char s3[23] = "hello, i'm an example!";

    // String s1 is alphabetically earlier than s2.
    assert(strcmp(s1, s2) < 0);
    // The first 5 chars of s2 and s3 are equal.
    assert(strncmp(s2, s3, 5) == 0);
}

Return Value

Upon completion, the strcmp() and strncmp() functions return an integer less than, equal to, or greater than zero if s1 (or the first n bytes thereof) is found respectively, to be less than, to match, or be greater than s2.

See Also

strcpy(), strncpy(), strlen()