C++中比较字符串需区分std::string和C风格字符串:前者用==、<等运算符或compare()方法,后者用strcmp()或strncmp()函数;注意std::string的比较是基于字符编码值,默认区分大小写,不区分大小写时需转换后再比较;常见错误是误用==比较char*指针内容而非地址,应避免;性能上,运算符更直观适合常规比较,compare()支持子串和三态结果,适用于复杂场景。

在C++中比较两个字符串,核心无非是两种情况:判断它们是否完全相同,或者确定它们在字典序上的前后关系。对于现代C++而言,最直观且推荐的方式是使用
std::string
==
<
char*
strcmp
谈到C++里的字符串比较,我们得区分开两种主要场景:
std::string
char*
1. std::string
这是C++标准库为我们提供的强大工具,我个人觉得,用起来简直是享受。它封装了内存管理,让我们可以专注于逻辑。
立即学习“C++免费学习笔记(深入)”;
相等性与不等性判断:==
!=
std::string
==
!=
#include <string>
#include <iostream>
int main() {
std::string s1 = "hello";
std::string s2 = "hello";
std::string s3 = "world";
if (s1 == s2) {
std::cout << "s1 and s2 are equal." << std::endl; // Output: s1 and s2 are equal.
}
if (s1 != s3) {
std::cout << "s1 and s3 are not equal." << std::endl; // Output: s1 and s3 are not equal.
}
return 0;
}字典序(Lexicographical)比较:<
>
<=
>=
#include <string>
#include <iostream>
int main() {
std::string a = "apple";
std::string b = "banana";
std::string c = "apricot";
if (a < b) {
std::cout << a << " comes before " << b << std::endl; // Output: apple comes before banana
}
if (a > c) { // 'p' == 'p', 'p' > 'r' is false, 'p' < 'r' is true
std::cout << a << " comes after " << c << std::endl;
} else {
std::cout << a << " comes before " << c << std::endl; // Output: apple comes before apricot
}
return 0;
}compare()
std::string
compare()
strcmp
#include <string>
#include <iostream>
int main() {
std::string s1 = "programming";
std::string s2 = "program";
if (s1.compare(s2) == 0) {
std::cout << "s1 and s2 are equal." << std::endl;
} else if (s1.compare(s2) < 0) {
std::cout << "s1 is lexicographically less than s2." << std::endl;
} else {
std::cout << "s1 is lexicographically greater than s2." << std::endl; // Output: s1 is lexicographically greater than s2.
}
// 比较子字符串:s1从索引0开始的7个字符与s2比较
if (s1.compare(0, 7, s2) == 0) {
std::cout << "First 7 chars of s1 are equal to s2." << std::endl; // Output: First 7 chars of s1 are equal to s2.
}
return 0;
}*2. C风格字符串(`char`)的比较**
如果你还在使用
char
char*
<cstring>
==
指针指向的字符串内容**,因为
strcmp()
strcmp(const char* s1, const char* s2)
\0
s1
s2
0
s1
s2
s1
s2
#include <cstring> // For strcmp
#include <iostream>
int main() {
const char* str1 = "apple";
const char* str2 = "apple";
const char* str3 = "banana";
if (strcmp(str1, str2) == 0) {
std::cout << "str1 and str2 are equal." << std::endl; // Output: str1 and str2 are equal.
}
if (strcmp(str1, str3) < 0) {
std::cout << "str1 comes before str3." << std::endl; // Output: str1 comes before str3.
}
// 错误示范:比较指针地址,而不是内容
if (str1 == str2) {
// 这通常不会成立,除非它们指向同一个内存地址
std::cout << "This might be misleading for content comparison." << std::endl;
}
return 0;
}strncmp()
strncmp(const char* s1, const char* s2, size_t n)
n
#include <cstring> // For strncmp
#include <iostream>
int main() {
const char* full_str = "programming";
const char* prefix = "program";
// 比较full_str的前7个字符和prefix
if (strncmp(full_str, prefix, 7) == 0) {
std::cout << "full_str starts with 'program'." << std::endl; // Output: full_str starts with 'program'.
}
return 0;
}是的,C++标准库提供的所有字符串比较操作,无论是
std::string
strcmp
"Hello"
"Hello"
那么,如果我们想实现不区分大小写的比较,该怎么办呢?这在很多实际应用中都非常常见,比如用户输入的校验、搜索功能等。
实现不区分大小写比较的方法,通常是在比较之前,将两个字符串都转换成统一的大小写格式(全部转为小写或全部转为大写),然后再进行比较。
一种比较直接的做法是:
逐字符转换并比较: 我们可以遍历两个字符串,对每个字符在比较前都进行大小写转换。这种方法的好处是避免了创建完整的临时字符串副本,对于内存敏感的场景可能更有利。
#include <string>
#include <iostream>
#include <cctype> // For std::tolower
// 辅助函数:将字符转为小写,处理EOF
char my_tolower(char ch) {
return static_cast<char>(std::tolower(static_cast<unsigned char>(ch)));
}
bool equalsIgnoreCase(const std::string& s1, const std::string& s2) {
if (s1.length() != s2.length()) {
return false;
}
for (size_t i = 0; i < s1.length(); ++i) {
if (my_tolower(s1[i]) != my_tolower(s2[i])) {
return false;
}
}
return true;
}
int main() {
std::string strA = "Hello World";
std::string strB = "hello world";
std::string strC = "HELLO C++";
if (equalsIgnoreCase(strA, strB)) {
std::cout << "'" << strA << "' and '" << strB << "' are equal ignoring case." << std::endl; // Output: 'Hello World' and 'hello world' are equal ignoring case.
}
if (!equalsIgnoreCase(strA, strC)) {
std::cout << "'" << strA << "' and '" << strC << "' are not equal ignoring case." << std::endl; // Output: 'Hello World' and 'HELLO C++' are not equal ignoring case.
}
return 0;
}这里
std::tolower
int
int
static_cast
unsigned char
char
创建临时小写(或大写)字符串: 另一种方法是先将两个字符串都完全转换成小写(或者大写)的临时字符串,然后再用普通的区分大小写比较方法进行比较。这种方法代码可能更简洁,但会涉及额外的内存分配和字符串复制,对性能敏感的场景需要权衡。
#include <string>
#include <iostream>
#include <algorithm> // For std::transform
#include <cctype> // For std::tolower
std::string toLower(std::string s) {
std::transform(s.begin(), s.end(), s.begin(),
[](unsigned char c){ return std::tolower(c); });
return s;
}
int main() {
std::string strX = "Example String";
std::string strY = "example string";
if (toLower(strX) == toLower(strY)) {
std::cout << "'" << strX << "' and '" << strY << "' are equal ignoring case." << std::endl; // Output: 'Example String' and 'example string' are equal ignoring case.
}
return 0;
}这种方式利用了
std::transform
需要注意的是,
std::tolower
std::toupper
std::tolower
std::string::compare()
std::string
==
<
>
compare()
1. 运算符重载 (==
!=
<
>
<=
>=
简洁性与直观性: 这是它们最大的优势。使用这些运算符,代码看起来非常自然,就像比较数字一样。它们返回布尔值(
true
false
功能: 主要用于判断两个完整的
std::string
适用场景: 绝大多数情况下,当你需要对整个字符串进行相等性或排序比较时,运算符重载是首选。它们是C++中最符合习惯的用法,代码可读性高。
std::string s_op1 = "abc";
std::string s_op2 = "abd";
if (s_op1 < s_op2) { // 直观判断字典序
// ...
}2. std::string::compare()
返回值:
compare()
int
strcmp
0
compare()
compare()
强大的子字符串比较能力: 这是
compare()
s1.compare(s2)
s1
s2
s1.compare(pos1, len1, s2)
s1
pos1
len1
s2
s1.compare(pos1, len1, s2, pos2, len2)
s1
pos1
len1
s2
pos2
len2
与C风格字符串的兼容性:
compare()
const char*
std::string s_comp1 = "programming";
std::string s_comp2 = "program";
const char* c_str_comp = "program";
// 比较s_comp1从索引0开始的7个字符与s_comp2
if (s_comp1.compare(0, 7, s_comp2) == 0) {
std::cout << "s_comp1 starts with s_comp2" << std::endl;
}
// 比较s_comp1从索引0开始的7个字符与C风格字符串
if (s_comp1.compare(0, 7, c_str_comp) == 0) {
std::cout << "s_comp1 starts with c_str_comp" << std::endl;
}
// 获取三态结果
int result = s_comp1.compare("programmer");
if (result < 0) {
std::cout << "s_comp1 < programmer" << std::endl;
}何时选用 compare()
我个人的经验是,如果你只是简单地判断两个完整的
std::string
然而,
compare()
compare()
compare()
compare()
compare()
std::string
const char*
compare()
总的来说,运算符重载是日常使用的“瑞士军刀”,而
compare()
在C++中处理字符串比较,虽然看起来简单,但实际上还是有一些陷阱和性能上的考考量。作为开发者,我们得留心这些细节,才能写出健壮高效的代码。
常见的错误:
==
const char* str1 = "hello"; const char* str2 = "hello";
if (str1 == str2)
以上就是如何在C++中比较两个字符串_C++字符串比较操作指南的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号