C++中比较字符串需根据类型选择方法:std::string可直接用==、<等运算符按字典序比较;C风格字符串须用strcmp函数,返回0为相等,负数为小于,正数为大于;忽略大小写时可用strcasecmp或_stricmp,或手动转小写再比较;禁用C风格字符串的==操作以防地址误判,推荐优先使用std::string。

在C++中,比较两个字符串的方法取决于你使用的是哪种字符串类型。最常见的两种是 std::string(来自标准库)和 C风格字符串(即字符数组或 const char*)。下面分别介绍它们的比较方式。
如果你使用的是 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;}
C 风格字符串不能直接用 == 比较内容,因为那会比较指针地址。必须使用标准库函数 strcmp 来比较内容。
strcmp(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;}
标准库没有提供忽略大小写的 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,可先转换为小写再比较,或写一个忽略大小写的比较函数。
基本上就这些。选择合适的方法取决于你的字符串类型和需求。std::string 更安全方便,C 风格字符串则需小心处理。
以上就是c++++怎么比较两个字符串_c++字符串比较方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号