在C++的标准库中,string类提供了多种字符串比较的方式,其中compare函数和==运算符是最常用的两种,很多开发者在初次使用时容易混淆两者的使用场景和差异。

两种比较方式的基础用法
==运算符的使用
==运算符是C++重载后的运算符,专门用于判断两个string对象的内容是否完全相等,使用方式非常直观,直接对两个字符串对象进行相等判断即可。
#include <iostream>
#include <string>
int main() {
std::string str1 = "hello";
std::string str2 = "hello";
std::string str3 = "world";
// 判断str1和str2是否相等
if (str1 == str2) {
std::cout << "str1和str2内容相等" << std::endl;
}
// 判断str1和str3是否相等
if (str1 == str3) {
std::cout << "str1和str3内容相等" << std::endl;
} else {
std::cout << "str1和str3内容不相等" << std::endl;
}
return 0;
}
compare函数的使用
compare函数是string类的成员函数,不仅可以判断两个字符串是否完全相等,还可以判断字符串的字典序大小,返回值有三种情况:返回0表示两个字符串相等,返回小于0的值表示当前字符串小于参数字符串,返回大于0的值表示当前字符串大于参数字符串。
#include <iostream>
#include <string>
int main() {
std::string str1 = "apple";
std::string str2 = "apple";
std::string str3 = "banana";
// 比较str1和str2
int res1 = str1.compare(str2);
if (res1 == 0) {
std::cout << "str1和str2相等" << std::endl;
}
// 比较str1和str3
int res2 = str1.compare(str3);
if (res2 < 0) {
std::cout << "str1小于str3" << std::endl;
}
return 0;
}
两者的核心差异对比
| 对比维度 | ==运算符 | compare函数 |
|---|---|---|
| 比较逻辑 | 仅判断两个字符串内容是否完全相等 | 可判断相等、小于、大于三种字典序关系 |
| 返回值 | 布尔值,true表示相等,false表示不相等 | 整数,0相等,小于0当前串小,大于0当前串大 |
| 使用场景 | 仅需判断字符串是否完全相同时使用 | 需要判断字符串大小关系或局部比较时使用 |
适用场景选择建议
如果只需要判断两个string对象的内容是否完全一致,优先使用==运算符,代码可读性更高,逻辑也更直观,其他开发者阅读代码时能快速理解判断意图。
如果需要判断字符串的字典序大小,或者需要比较两个字符串的指定子串,就需要使用compare函数,它提供了多个重载版本,可以指定比较的起始位置和长度。
#include <iostream>
#include <string>
int main() {
std::string str = "hello world";
// 比较str从6开始的5个字符和"world"是否相等
int res = str.compare(6, 5, "world");
if (res == 0) {
std::cout << "指定子串和world相等" << std::endl;
}
return 0;
}
注意事项
- 使用
==运算符比较时,会先判断两个string对象的长度是否相等,长度不等直接返回false,长度相同再逐字符比较,效率较高。 compare函数比较时也是逐字符按照字典序比较,直到出现不同的字符或者比较完所有字符,不要误以为它仅比较字符串长度。- 不要用
compare函数的返回值直接作为布尔条件判断相等,比如if (str1.compare(str2))这种写法是错误的,因为返回0才表示相等,非0表示不相等。