strcmp

From Wikipedia, the free encyclopedia


In the programming language C, strcmp is a function in the C standard library (declared in string.h) that compares two C strings.

The prototype according ISO/IEC 9899:1999, 7.21.4.2

int strcmp(const char *s1, const char *s2);

strcmp returns 0 when the strings are equal, a negative integer when s1 is less than s2, or a positive integer if s1 is greater than s2, according to the lexicographical order.

A variant of strcmp exists called strncmp that only compares the strings up to a certain point.

[edit] Example

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
int main (int argc, char **argv)
{
    int v;
 
    if (argc < 3)
    {
        fprintf (stderr, "This program takes 2 arguments.\n");
        return EXIT_FAILURE;
    }
 
    v = strcmp (argv[1], argv[2]);
 
    if (v < 0)
        printf ("'%s' is less than '%s'.\n", argv[1], argv[2]);
    else if (v == 0)
        printf ("'%s' equals '%s'.\n", argv[1], argv[2]);
    else if (v > 0)
        printf ("'%s' is greater than '%s'.\n", argv[1], argv[2]);
 
    return 0;
}

The above code is a working sample that prints whether the first argument is less than, equal to or greater than the second.

A possible implementation is (P.J. Plauger, The Standard C Library, 1992):

int strcmp (const char * s1, const char * s2)
{
 
    for(; *s1 == *s2; ++s1, ++s2)
        if(*s1 == 0)
            return 0;
    return *(unsigned char *)s1 < *(unsigned char *)s2 ? -1 : 1;
}

However, most real-world implementations will have various optimization tricks to reduce the execution time of the function.


Languages