c++判断字符串相等
时间: 2025-01-21 22:07:56 浏览: 46
### C++ 中字符串比较方法
在 C++ 中,`std::string` 类提供了多种方式来实现字符串之间的相等性检查。
#### 使用 `==` 运算符
最简单的方式是利用重载后的等于运算符 (`==`) 来对比两个字符串的内容是否相同。这种方式直观易懂,并且性能良好[^1]。
```cpp
#include <iostream>
#include <string>
int main() {
std::string s1 = "hello";
std::string s2 = "world";
bool isEqual = (s1 == s2);
std::cout << ((isEqual) ? "Equal" : "Not Equal") << std::endl;
}
```
#### 调用成员函数 compare()
除了使用运算符外,还可以调用 `std::string` 的内置成员函数 `compare()` 。此函数返回0表示两串完全一致;小于零意味着左侧字典序更前;大于零则相反。
```cpp
#include <iostream>
#include <string>
int main(){
std::string str1="example", str2="sample";
int result=str1.compare(str2);
if(result<0){
std::cout<<str1<<" comes before "<<str2<<'\n';
}
else if(result>0){
std::cout<<str1<<" comes after "<<str2<<'\n';
}
else{
std::cout<<str1<<" is equal to "<<str2<<'\n';
}
return 0;
}
```
阅读全文
相关推荐


















