#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。==, <, > 等运算符直接比较两个字符串的内容。这些运算符会根据字典顺序进行比较。std::string 类提供了一个 compare 成员函数,用于比较两个字符串。返回值为 0 表示相等,负数表示第一个字符串小于第二个字符串,正数表示第一个字符串大于第二个字符串。通过这两种方式,你可以轻松地在 C++ 中比较字符串。
上一篇:c++ dll
下一篇:c++ emplace_back
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站