compare

Syntax:

    #include <string>
    int compare( const string& str ) const;
    int compare( const Char* str ) const;
    int compare( size_type index, size_type length, const string& str ) const;
    int compare( size_type index, size_type length, const string& str, size_type index2, size_type length2 ) const;
    int compare( size_type index, size_type length, const Char* str, size_type length2 = npos ) const;

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 each other:

   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-11-1
“Marge”.compare( x )101-1
“3-eyed fish”.compare( x )-1-10-1
“inanimate carbon rod”.compare( x )1110

Related Topics: String operators