Strcmp
From Wikipedia, the free encyclopedia
- The correct title of this article is strcmp. The initial letter is shown capitalized due to technical restrictions.
In the programming language C, strcmp is a function in the C standard library (in the string.h header file) that compares two C strings.
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 <string.h> int main (int argc, char **argv) { if (argc < 3) { fprintf (stderr, "This program takes 2 arguments.\n"); return 1; } int 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.