TOC | Prev | Next

String comparisons

You can't simply say if ( a == b ) or if ( a < b ). You have
to use strcmp.

If a comes after b, then strcmp(a,b) returns a positive int.

If a comes before b, then strcmp(a,b) returns a negative int.

If a equals b, then strcmp(a,b) returns zero.

For case-insensitive comparisons, use a function like strcmpi.

There doesn't seem to be a standard for the name of strcmpi, which
seems to be strcasecmp under GCC.

strcmp.c

#include <stdio.h>
#include <string.h>

int main( void ) {
    const char *a = "Foo";
    const char *b = "Bar";
    const char *c = "foo";

    printf( "strcmp( \"%s\", \"%s\" ) = %d\n", a, b, strcmp( a, b ) );
    printf( "strcmp( \"%s\", \"%s\" ) = %d\n", a, c, strcmp( a, c ) );
    printf( "strcasecmp( \"%s\", \"%s\" ) = %d\n", a, b, strcasecmp( a, b ) );
    printf( "strcasecmp( \"%s\", \"%s\" ) = %d\n", a, c, strcasecmp( a, c ) );

    return 0;
}

$ strcmp

strcmp( "Foo", "Bar" ) = 4
strcmp( "Foo", "foo" ) = -32
strcasecmp( "Foo", "Bar" ) = 4
strcasecmp( "Foo", "foo" ) = 0
TOC | Prev | Next