This documentation is copyright © 1998-2001 Sandro Sigala <sandro@sigala.it>.
All rights reserved.
Released under the GNU General Public License.
strcmp
Prototype
#include <string.h>
int strcmp(const char *s1, const char *s2);
Description
Compares the two strings s1
and s2
character by character
up to the terminating null character. 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
.
Implementation
#include <string.h>
int strcmp(const char *s1, const char *s2)
{
const unsigned char *sp1 = (const unsigned char *)s1;
const unsigned char *sp2 = (const unsigned char *)s2;
for (; *sp1 == *s2; ++sp1, ++sp2)
if (*sp1 == '\0')
return 0;
return *sp1 - *sp2;
}
Example
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
* cmpstr.c: compare the two argument strings.
* usage: cmpstr <string1> <string2>
*/
int main(int argc, char **argv)
{
int i;
if (argc != 3) {
fprintf(stderr, "usage: %s <string1> <string2>\n",
argv[0]);
return EXIT_FAILURE;
}
i = strcmp(argv[1], argv[2]);
printf("`%s' is %s `%s'\n", argv[1],
((i > 0) ? "greater than" :
(i < 0) ? "less than" : "equal to"), argv[2]);
return EXIT_SUCCESS;
}
References
ISO C 9899:1990 7.11.4.2