SYNOPSIS
       #include 

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

       int strncmp(const char *s1, const char *s2, size_t n);
DESCRIPTION
strcmp compares s1 and s2. It returns the integer equivalent of s1 - s2. If s1 is greater, less than, or equal to, s2, it returns a number greater than, less than, or equal to 0, respectively.

strncmp does the same thing, but only for the first n characters.

NOTES
This is a very useful str function. You'll see it a lot whilst coding in C.

Of course, in most other languages you just say:

JavaScript/PERL/PHP:
foo = "1";
bar = "2";

Javascript: if(foo == bar) {
PERL:       if(bar eq foo) {
PHP          if(foo == bar) {
But this is C, so we do it like this:

    const char foo[]    = "a string";
    const char bar[]    = "another string";

    if ( strcmp( bar, foo ) == 0 ) 
        puts( "they're the same" );
Not that this is a problem - after all, C is supposed to be more of a human readable assembly than it is a magical string manipulation language. And you do get rather more power when you deal with strings in the C fashion, although it takes longer to get used to...

It's all about tradeoffs. C may be faster and more powerful, but you also have to know what you're doing. ;)


Many, many thanks to wharfinger, who was kind enough to correct my horrendous example of C string comparison. In retrospect, it may have been wise to name my variables. (That's certainly why I couldn't figure out where to put the array brackets.)
I hope you'll forgive me, wharfinger - I snipped up your example a bit, because I wanted to make it more homogenous with the pre-existing examples.

Log in or register to write something here or to contact authors.