C++ string compare関数:文字列比較の基本と応用
C++では、stringのcompare関数を使って2つのstringオブジェクトのサイズを比較することができます。関数のプロトタイプは次のようになります:
int compare(const string& str) const;
この関数を呼び出すと、現在の文字列オブジェクトがstrよりも小さい場合は負の値を返し、現在の文字列オブジェクトがstrよりも大きい場合は正の値を返します。そして、もし二つの文字列オブジェクトが等しい場合は0を返します。
例えば、
#include <iostream>
#include <string>
int main() {
std::string str1 = "hello";
std::string str2 = "world";
if (str1.compare(str2) < 0) {
std::cout << "str1 is less than str2" << std::endl;
} else if (str1.compare(str2) > 0) {
std::cout << "str1 is greater than str2" << std::endl;
} else {
std::cout << "str1 is equal to str2" << std::endl;
}
return 0;
}
結果は次の通りです:
str1 is less than str2