c++string判断是否相等
时间: 2023-11-24 18:49:15 浏览: 205
在C++中,判断两个string类型的字符串是否相等可以使用比较运算符"=="或者使用string类的成员函数compare()。使用比较运算符"=="时,只需要将两个字符串进行比较即可,如果相等则返回true,否则返回false。使用string类的成员函数compare()时,如果两个字符串相等,则返回0,否则返回一个非0值。下面是两种方法的示例代码:
1.使用比较运算符"=="
```
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1 = "hello";
string str2 = "world";
if (str1 == str2) {
cout << "str1等于str2" << endl;
} else {
cout << "str1不等于str2" << endl;
}
return 0;
}
```
2.使用string类的成员函数compare()
```
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1 = "hello";
string str2 = "world";
int result = str1.compare(str2);
if (result == 0) {
cout << "str1等于str2" << endl;
} else {
cout << "str1不等于str2" << endl;
}
return 0;
}
```