Translations of this page?:

compare

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:

  • comparam str à string actual,
  • comparam str a uma substring da string actual, começando em index para length caracteres,
  • comparam uma substring de str a uma substring da string actual, onde index2 e length2 referem-se a str, e index e length referem-se à string actual,
  • ou comparam uma substring de str a uma substring da string actual, onde a substring de str começa em zero e tem comprimento length2, e a substring da string actual começa em index e tem length caracteres.

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

Tópicos Relacionados: String_operators

 
• • • SitemapRecent changesRSScc