#include <iostream>
#include <string>
int main() {
// 定义两个字符串
std::string str1 = "hello";
std::string str2 = "world";
// 使用比较运算符进行字符串比较
if (str1 == str2) {
std::cout << "str1 和 str2 相等" << std::endl;
} else if (str1 < str2) {
std::cout << "str1 小于 str2" << std::endl;
} else {
std::cout << "str1 大于 str2" << std::endl;
}
// 使用 compare 函数进行字符串比较
int result = str1.compare(str2);
if (result == 0) {
std::cout << "str1 和 str2 相等" << std::endl;
} else if (result < 0) {
std::cout << "str1 小于 str2" << std::endl;
} else {
std::cout << "str1 大于 str2" << std::endl;
}
return 0;
}
std::string
类型定义了两个字符串 str1
和 str2
。==
, <
, >
等运算符来比较两个字符串。这些运算符会根据字典顺序(即字符的 ASCII 值)进行比较。std::string
提供了 compare
成员函数,返回值为整数:0
表示两个字符串相等。这段代码展示了两种常见的字符串比较方法,并输出比较结果。
上一篇:c++ filesystem
下一篇:c++ function
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站