string 判断相等 c++
时间: 2025-03-27 18:17:45 浏览: 34
### C++ 中字符串相等比较
在 C++ 中,`std::string` 对象提供了多种方式进行比较操作。对于两个 `std::string` 类型的变量之间的相等性判断,可以直接使用等于运算符 (`==`) 来完成这一任务[^3]。
下面是一个简单的例子来展示如何实现这一点:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str1 = "hello";
std::string str2 = "world";
std::string str3 = "hello";
if (str1 == str3) {
std::cout << "str1 and str3 are equal." << std::endl;
} else {
std::cout << "str1 and str3 are not equal." << std::endl;
}
if (str1 == str2) {
std::cout << "str1 and str2 are equal." << std::endl;
} else {
std::cout << "str1 and str2 are not equal." << std::endl;
}
}
```
当涉及到不同类型的字符串(例如 C 风格字符串与 `std::string`),也可以通过相同的运算符来进行比较,因为 C 风格字符串会自动转换成 `std::string` 类型再做对比[^4]。
阅读全文
相关推荐


















