Sintaxe:
#include <string> int compare( const string& str ) const; int compare( const charT* 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 charT* str, size_type length2 = npos ) const;
A função compare() compara str à string actual de várias maneiras, devolvendo
| Valor devolvido | Caso |
|---|---|
| menor que zero | this < str |
| zero | this == str |
| maior que zero | this > str |
As várias funções:
Por exemplo, o código seguinte usa compare() para comparar quatro strings entre si:
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; }
Dados do código acima foram usados para gerar esta tabela, que mostra como as várias strings se comparam entre si:
| 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 |
Tópicos Relacionados: String_operators