strcmp() — Compare Strings

Format

#include <string.h>
int strcmp(const char *string1, const char *string2);

Language Level: ANSI

Threadsafe: Yes.

Description

The strcmp() function compares string1 and string2. The function operates on null-ended strings. The string arguments to the function should contain a null character (\0) that marks the end of the string.

Return Value

The strcmp() function returns a value indicating the relationship between the two strings, as follows:

Value Meaning
Less than 0 string1 less than string2
0 string1 identical to string2
Greater than 0 string1 greater than string2

Example that uses strcmp()

This example compares the two strings that are passed to main() using strcmp().

#include <stdio.h>
#include <string.h>
 
int main(int argc, char ** argv)
{
  int  result;
 
  if ( argc != 3 )
  {
    printf( "Usage: %s string1 string2\n", argv[0] );
  }
  else
  {
 
    result = strcmp( argv[1], argv[2] );
 
    if ( result == 0 )
      printf( "\"%s\" is identical to \"%s\"\n", argv[1], argv[2] );
    else if ( result < 0 )
      printf( "\"%s\" is less than \"%s\"\n", argv[1], argv[2] );
    else
      printf( "\"%s\" is greater than \"%s\"\n", argv[1], argv[2] );
  }
}
 
/******************  If the input is the strings  ***********************
**********  "is this first?" and "is this before that one?",  ***********
******************  then the expected output is:  *********************
 
"is this first?" is greater than "is this before that one?"
**********************************************************************/

Related Information



[ Top of Page | Previous Page | Next Page | Contents | Index ]