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:

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