compare
描述 (Description)
它将字符串对象(或子字符串)的值与其参数指定的字符序列进行比较。
声明 (Declaration)
以下是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;
参数 (Parameters)
str - 它是一个字符串对象。
len - 用于复制字符。
pos - 要复制的第一个字符的位置。
返回值 (Return Value)
它返回一个有符号的整数,表示字符串之间的关系。
异常 (Exceptions)
如果抛出异常,则字符串中没有变化。
例子 (Example)
在下面的示例中,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