文字列辞書順を比較する3つの方法【C++】


1 strcmp(s1, s2)
C言語では,strcmp()関数を用いてchar*型文字列のディクショナリシーケンスを比較することができる.
  • 文字列s 1の辞書順が文字列s 2の辞書順より小さい場合、値<0を返します.
  • 文字列s 2のディクショナリシーケンスが文字列s 1のディクショナリシーケンスより大きい場合、値>0が返されます.
  • 文字列s 1のディクショナリ順序が文字列s 2のディクショナリ順序に等しい場合、値=0を返します.
  • #include 
    using namespace std;
    
    int main() {
         
    	char s1[2] = "a";
    	char s2[2] = "b";
    	cout << strcmp(s1, s2) << endl;	//-1
    	cout << strcmp(s2, s1) << endl;	//1
    	cout << strcmp(s1, s1) << endl;	//0
    	return 0;
    }
    

    2 s1.compare(s2)
    C++では、compare()関数を使用して、char*タイプとstringタイプの文字列のディクショナリシーケンスを比較できます.compare()関数とstrcmp()関数の戻り値は同じです.
    #include 
    #include 
    using namespace std;
    
    int main() {
         
    	string s1 = "a";
    	string s2 = "b";
    	cout << s1.compare(s2) << endl;	//-1
    	cout << s2.compare(s1) << endl;	//1
    	cout << s1.compare(s1) << endl;	//0
    	return 0;
    }
    

    3 <
    また、C++では、比較演算子を使用してchar*タイプとstringタイプの文字列のディクショナリシーケンスを比較することもできます.比較演算子を使用してchar*タイプの文字列を比較する場合は、char*タイプをstringタイプに強制的に変換する必要があります.そうしないと、比較するのは文字列の開始アドレスです.
    #include 
    using namespace std;
    
    int main() {
         
    	char s1[2] = "a";
    	char s2[2] = "b";
    	cout << (s1 < s2) << endl;	//0
    	cout << &s1 << endl;		//00BDFE74
    	cout << &s2 << endl;		//00BDFE68
    	cout << (string(s1) < string(s2)) << endl;	//1
    	cout << (string(s2) < string(s1)) << endl;	//0
    	cout << (string(s1) == string(s1)) << endl;	//1
    	return 0;
    }