C++中比较字符串需根据类型选择方法:std::String可直接用==、<等运算符按字典序比较;C风格字符串须用strcmp函数,返回0为相等,负数为小于,正数为大于;忽略大小写时可用strcasecmp或_stricmp,或手动转小写再比较;禁用C风格字符串的==操作以防地址误判,推荐优先使用std::string。
在C++中,比较两个字符串的方法取决于你使用的是哪种字符串类型。最常见的两种是 std::string(来自标准库)和 C风格字符串(即字符数组或 const char*)。下面分别介绍它们的比较方式。
1. 使用 std::string 进行比较
如果你使用的是 std::string,可以直接使用比较运算符,因为标准库已经重载了这些操作符。
支持的操作包括:==, !=, <, >, <=, >=
这些操作按字典序进行比较。
立即学习“C++免费学习笔记(深入)”;
示例代码:
#include <iostream> #include <string> using namespace std; <p>int main() { string str1 = "apple"; string str2 = "banana";</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">if (str1 == str2) { cout << "相等" << endl; } else if (str1 < str2) { cout << "str1 小于 str2" << endl; // 输出这行 } return 0;
}
2. 使用 C 风格字符串(char* 或字符数组)
C 风格字符串不能直接用 == 比较内容,因为那会比较指针地址。必须使用标准库函数 strcmp 来比较内容。
strcmp(s1, s2) 返回值含义:
- 返回 0:s1 和 s2 相等
- 返回负数:s1 字典序小于 s2
- 返回正数:s1 字典序大于 s2
示例代码:
#include <iostream> #include <cstring> // 注意包含 cstring using namespace std; <p>int main() { const char<em> s1 = "hello"; const char</em> s2 = "world";</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">if (strcmp(s1, s2) == 0) { cout << "两个字符串相等" << endl; } else { cout << "不相等" << endl; } return 0;
}
3. 忽略大小写的字符串比较
标准库没有提供忽略大小写的 std::string 比较函数,但可以自己实现或使用平台相关函数。
linux/unix 下可用 strcasecmp,windows 下可用 _stricmp。
示例(Linux):
#include <iostream> #include <cstring> using namespace std; <p>int main() { const char<em> s1 = "Hello"; const char</em> s2 = "hello";</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">if (strcasecmp(s1, s2) == 0) { cout << "忽略大小写时相等" << endl; } return 0;
}
如果使用 std::string,可先转换为小写再比较,或写一个忽略大小写的比较函数。
4. 常见错误提醒
- 不要对 C 风格字符串使用 == 比较内容,它比较的是地址
- 确保字符串以 ‘