Menu
CoddyTech

字符串比较

本课属于 Coddy C++ 学习旅程的“基础知识”单元。第 22 课,共 74 课。

在 C++ 中,可以用多种方式比较字符串。由于 std::string 是一个类,它重载了运算符,因此字符串比较直观又简单。

比较字符串最常见的方法是使用比较运算符(==、!=、<、>、<=、>=):

string str1 = "hello";
string str2 = "hello";
string str3 = "Hello";

bool result1 = (str1 == str2);  // true
bool result2 = (str1 == str3);  // false(区分大小写)
bool result3 = (str1 != str3);  // true

你也可以使用 compare() 方法。如果字符串相等,它会返回 0;如果第一个字符串按字典序小于第二个字符串,则返回一个负整数;如果第一个字符串较大,则返回一个正整数。请注意,具体返回值由实现决定,不一定是 -1 或 1:

string str1 = "a";
string str2 = "b";
string str3 = "c";

cout << str2.compare(str1) << endl; 
// 正数(b 排在 a 后面)

cout << str2.compare(str3) << endl;
// 负数(b 排在 c 前面)

cout << str2.compare(str2) << endl;
// 0(字符串相同)

亲手试试

这节课没有代码挑战。

quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

基础知识中的所有课

自己练习: C++ 在线编译器