In POSIX and 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 offset.
Another variant, strcasecmp
, conforming to POSIX.1-2001, works like strcmp
, but is case-insensitive. Some systems instead provide this functionality with functions named stricmp
or strcmpi
. To compare a subset of both strings with case-insensitivity, various systems may provide strncasecmp
, strnicmp
or strncmpi
.
Example
[edit | edit source]
#include <stdio.h>#include <stdlib.h>#include <string.h>int main (int argc, char **argv){ int v; if (argc < 3) { fprintf (stderr, "Compares two strings\nUsage: %s string1 string2\n",argv[0]); 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. One will notice, that strcmp not only returns -1, 0 and +1, but also other negative or positive values, resulting from optimizing away the branching introduced by the ?:
operator:
return *(const unsigned char *)s1 - *(const unsigned char *)s2;
See also
[edit | edit source]
External links
[edit | edit source]