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 = npos );
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 | -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 |
Related Topics: String operators