compare
Syntax:
  #include <string>
  int compare( const string& str );
  int compare( const char* str );
  int compare( size_type index, size_type length, const string& str );
  int compare( size_type index, size_type length, const string& str, size_type index2,
  size_type length2 );
  int compare( size_type index, size_type length, const char* str, size_type length2 );

The compare() function either compares str to the current string in a variety of ways, returning

Return Value Case
less than zero this < str
zero this == str
greater than zero this > str

The various functions either:

  • compare str to the current string,
  • compare str to a substring of the current string, starting at index for length characters,
  • compare a substring of str to a substring of the current string, where index2 and length2 refer to str and index and length refer to the current string,
  • or compare a substring of str to a substring of the current string, where the substring of str begins at zero and is length2 characters long, and the substring of the current string begins at index and is length characters long.

For example, the following code uses compare() to compare four strings with eachother:

 string names[] = {"Homer", "Marge", "3-eyed fish", "inanimate carbon rod"};            

 for( int i = 0; i < 4; i++ ) {
   for( int j = 0; j < 4; j++ ) {
     cout << names[i].compare( names[j] ) << " ";
   }
   cout << endl;
 }              

Data from the above code was used to generate this table, which shows how the various strings compare to eachother:

Homer Marge 3-eyed fish inanimate carbon rod
"Homer".compare( x ) 0 -1 1 -1
"Marge".compare( x ) 1 0 1 -1
"3-eyed fish".compare( x ) -1 -1 0 -1
"inanimate carbon rod".compare( x ) 1 1 1 0