C++中字符串比较核心是内容或字典序的对比,主要通过重载运算符(如==、

C++中比较两个字符串,核心上是判断它们的内容是否相同,或者在字典序上的先后关系。这通常通过重载的比较运算符(如
==
、
<
等)或
std::string
类提供的
compare()
成员函数来完成。性能方面,主要取决于字符串的长度和比较的策略,但现代C++标准库的实现通常已经高度优化,大部分情况下我们无需过度担心,除非是在极端性能敏感的场景。
解决方案
在C++里,处理字符串比较有几种常用的方式,每种都有其适用场景。我个人在日常开发中,会根据具体需求灵活选择。
使用比较运算符(
==
==
,
!=
,
<
,
>
,
<=
,
>=
)
对于
std::string
对象,C++标准库已经重载了这些比较运算符,它们执行的是字典序(lexicographical)比较。说白了,就是像查字典一样,从头开始逐个字符地比较它们的ASCII或Unicode值,直到遇到第一个不同的字符,或者其中一个字符串结束。
#include #include int main() { std::string s1 = "apple"; std::string s2 = "banana"; std::string s3 = "apple"; std::string s4 = "apricot"; // 相等比较 if (s1 == s3) { std::cout << "s1 和 s3 内容相同。" << std::endl; // 输出 } // 不等比较 if (s1 != s2) { std::cout << "s1 和 s2 内容不同。" << std::endl; // 输出 } // 字典序小于 if (s1 < s2) { // 'a' == 'a', 'p' < 'b' (false), 'p' < 'a' (false) ... wait, 'p' < 'b' is false. 'a' < 'b' is true. // Let's re-evaluate: 'a' == 'a', 'p' == 'p', 'p' == 'p', 'l' "apple". std::cout << "s1 在字典序上小于 s2。" < s1) { // 'a' == 'a', 'p' == 'p', 'r' > 'p' std::cout << "s4 在字典序上大于 s1。" << std::endl; // 输出 } return 0;}
这种方式是我最常用的,因为它直观、简洁,符合我们日常对字符串比较的直觉。
立即学习“C++免费学习笔记(深入)”;
使用
std::string::compare()
std::string::compare()
方法
std::string
提供了一个
compare()
成员函数,它比运算符提供了更细粒度的控制,比如你可以比较字符串的子串。它的返回值是一个整数:
-
0
表示两个字符串(或子串)相等。
小于0
表示当前字符串(或子串)在字典序上小于另一个。
大于0
表示当前字符串(或子串)在字典序上大于另一个。
compare()
有多个重载版本,最常用的可能是:
-
int compare(const string& str) const;
比较整个字符串。
int compare(size_type pos, size_type len, const string& str) const;
比较当前字符串从
pos
开始,长度为
len
的子串与
str
。
int compare(size_type pos, size_type len, const string& str, size_type subpos, size_type sublen) const;
比较当前字符串的子串与另一个字符串的子串。
#include #include int main() { std::string s1 = "hello world"; std::string s2 = "world"; if (s1.compare(s2) != 0) { std::cout << "s1 和 s2 不完全相同。" << std::endl; // 输出 } // 比较 s1 的子串 "world" 与 s2 if (s1.compare(6, 5, s2) == 0) { // 从索引6开始,长度5的子串是"world" std::cout << "s1 的子串 'world' 和 s2 相同。" << std::endl; // 输出 } return 0;}C风格字符串(
char*
char*
)的比较
如果你处理的是C风格字符串(
char*
),那么需要使用C标准库中的
strcmp
或
strncmp
函数。这些函数在
头文件中。需要特别注意的是,这些函数要求字符串以空字符