#include <iostream>
#include <string>
int main() {
std::string str1 = "hello";
std::string str2 = "world";
std::string str3 = "hello";
// 比较两个字符串是否相等
if (str1 == str2) {
std::cout << "str1 and str2 are equal" << std::endl;
} else {
std::cout << "str1 and str2 are not equal" << std::endl;
}
// 使用 compare 函数比较两个字符串
if (str1.compare(str3) == 0) {
std::cout << "str1 and str3 are equal" << std::endl;
} else {
std::cout << "str1 and str3 are not equal" << std::endl;
}
// 比较部分字符串
std::string long_str = "hello world";
if (long_str.compare(0, 5, "hello") == 0) {
std::cout << "The first 5 characters of long_str are 'hello'" << std::endl;
}
return 0;
}
== 运算符可以直接比较两个 std::string 是否相等。std::string 类提供了 compare 方法,可以更灵活地进行字符串比较。返回值为 0 表示两个字符串相等,负数表示第一个字符串小于第二个字符串,正数表示第一个字符串大于第二个字符串。compare 方法还可以用于比较字符串的某一部分,例如从指定位置开始的若干字符。上一篇:c++练习
下一篇:c++ 分割字符串
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站