Previous Page
Next Page

strcmp

Compares two strings

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

The strcmp( ) function compares the strings addressed by its two pointer arguments, and returns a value indicating the result as follows:


Zero

The two strings are equal.


Greater than zero

The string addressed by s1 is greater than the string addressed by s2.


Less than zero

The string addressed by s1 is less than the string addressed by s2.

The strcmp( ) function compares the strings, one character at a time. As soon as it finds unmatched characters in corresponding positions in the two strings, the string containing the greater unsigned character value at that position is the greater string.

Example

int result = 0;
char word1[256], word2[256], *greaterlessequal;

while ( result < 2 )
{
  puts( "Type two words, please." );
  result = scanf( "%s%s", word1, word2 );
}
result = strcmp( word1, word2 );

if ( result < 0 )
  greaterlessequal = "less than";
else if ( result > 0 )
  greaterlessequal = "greater than";
else
  greaterlessequal = "the same as";

printf( "The word \"%s\" is %s the word \"%s\".\n",
        word1, greaterlessequal, word2 );

See also the example for qsort( ) in this chapter.

See Also

strncmp( ), memcmp( ), wcscmp( )


Previous Page
Next Page