compare
提供:cppreference.com
Syntax:
#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;
compare()関数は、"str"を現在の文字列といくつかの比較結果を返します。
| 返り値 | 条件 |
|---|---|
| 0より小さい | this < str |
| 0 | this == str |
| 0より大きい | this > str |
様々な機能
- "str"と現在の文字列の比較をする。
- "str"と現在の文字列の差分を比較する、部分文字列は、"index"位置から"length"まで
- "str"の部分文字列と現在の文字列の差分を比較する、現在の部分文字列は、"index"位置から"length"まで、"str"の部分文字列は、"index2"位置から"length2"まで
- またはここでは、現在の文字列の部分文字列strの文字列を比較する、"str"の部分文字列は、ゼロから始まり、length2文字の長さとなり、現在の文字列の部分文字列には、indexから始まり、length文字の長さです。
たとえば、次のコードでは、他の4つの文字列を比較するためにcompare()を使用します。
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; }
上記コードを実行すると、次の表の結果が得られます。表の値は、文字列を比較した結果です。
| 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 |
Related Topics: String_operators