Przestrzenie nazw
Warianty
Działania

compare

Z cppreference.com

Składnia:

#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;

Metoda compare() porównuje obecny string (this) z str:

Wartość zwracana W przypadku
mniejsza od zera this < str
zero this == str
większa od zera this > str

Różne metody:

  • porównuje string obecny z str,
  • porównuje podciąg obecnego stringa od pozycji index mający lenght znaków z str
  • porównuj podciąg obecnego stringa z podciągiem str, gdzie index i lenght odnosi się do obecnego, a index2 i lenght2 odnosi się do str
  • porównuje podciąg obecnego stringa z prefiksem str, gdzie index i lenght odnosi się do obecnego, a lenght2 jest długością prefiksu str


Na przykład poniższy kod używa compare() by porównać 4 stringi z każdym pozostałym.

 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;}

Powyższy kod generuje tabelę:

Homer Marge 3-eyed fish inanimate carbon rod
"Homer".compare( x ) 0
1
"Marge".compare( x ) 1 0 1
"3-eyed fish".compare( x )
0
"inanimate carbon rod".compare( x ) 1 1 1 0

Powiązane tematy: String_operators

close