📅  最后修改于: 2023-12-03 14:59:50.893000             🧑  作者: Mango
在C++中,std::字符串::compare()是一种比较两个字符串的方法。它接收一个字符串作为参数,并返回一个整数。如果两个字符串相等,它返回0。如果第一个字符串大于第二个字符串,则返回一个正整数,如果第一个字符串小于第二个字符串,则返回一个负整数。
int compare(const std::string &str) const noexcept;
str:
要比较的字符串。
整数值:
注意,compare()方法是区分大小写的。如果您想要一个不区分大小写的比较方法,则可以使用std::字符串::comparei()。
#include <iostream>
#include <string>
int main()
{
std::string str1 = "hello world";
std::string str2 = "Hello world!";
std::string str3 = "hello";
std::cout << "str1.compare(str2) = " << str1.compare(str2) << std::endl;
std::cout << "str2.compare(str1) = " << str2.compare(str1) << std::endl;
std::cout << "str1.compare(str3) = " << str1.compare(str3) << std::endl;
std::cout << "str3.compare(str1) = " << str3.compare(str1) << std::endl;
std::cout << "str3.compare(str1.substr(0, 5)) = " << str3.compare(str1.substr(0, 5)) << std::endl;
return 0;
}
输出:
str1.compare(str2) = 1
str2.compare(str1) = -1
str1.compare(str3) = 6
str3.compare(str1) = -6
str3.compare(str1.substr(0, 5)) = 0
在上面的示例中,我们比较了几个字符串。请注意,如果两个字符串不同,它们的比较结果将是它们第一个不匹配字符的ASCII代码的差值。如果有多个不匹配的字符,则只考虑第一个不匹配字符。如果str1是str2的前缀,则str3.compare(str1.substr(0, 5))返回0。