C++ String 库 - compare
描述
它将字符串对象(或子字符串)的值与其参数指定的字符序列进行比较。
声明
以下是 std::string::compare 的声明。
int compare (size_t pos, size_t len, const string& str) const; int compare (size_t pos, size_t len, const string& str, size_t subpos, size_t sublen) const;
C++11
int compare (size_t pos, size_t len, const string& str) const; int compare (size_t pos, size_t len, const string& str, size_t subpos, size_t sublen) const;
C++14
int compare (size_t pos, size_t len, const string& str) const; int compare (size_t pos, size_t len, const string& str, size_t subpos, size_t sublen = npos) const;
参数
str − 它是一个字符串对象。
len − 它用于复制字符。
pos − 要复制的第一个字符的位置。
返回值
它返回一个有符号整数,指示字符串之间的关系。
异常
如果抛出异常,则字符串没有变化。
示例
在下面的 std::string::compare 示例中。
#include <iostream> #include <string> int main () { std::string str1 ("green mango"); std::string str2 ("red mango"); if (str1.compare(str2) != 0) std::cout << str1 << " is not " << str2 << '\n'; if (str1.compare(6,5,"mango") == 0) std::cout << "still, " << str1 << " is an mango\n"; if (str2.compare(str2.size()-5,5,"mango") == 0) std::cout << "and " << str2 << " is also an mango\n"; if (str1.compare(6,5,str2,4,5) == 0) std::cout << "therefore, both are mangos\n"; return 0; }
示例输出应该是这样的 −
green mango is not red mango still, green mango is an mango and red mango is also an mango therefore, both are mangos