c++判断两个字符串是否相等
时间: 2023-08-06 12:07:04 浏览: 125
在C++中判断两个字符串是否相等可以使用字符串比较函数`strcmp()`,该函数接受两个字符串参数,如果两个字符串相等则返回0,否则返回非0值。示例代码如下:
```c++
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char str1[] = "Hello";
char str2[] = "world";
char str3[] = "Hello";
if (strcmp(str1, str2) == 0) {
cout << "str1 and str2 are equal" << endl;
} else {
cout << "str1 and str2 are not equal" << endl;
}
if (strcmp(str1, str3) == 0) {
cout << "str1 and str3 are equal" << endl;
} else {
cout << "str1 and str3 are not equal" << endl;
}
return 0;
}
```
输出结果为:
```
str1 and str2 are not equal
str1 and str3 are equal
```
另外,如果使用`std::string`类型存储字符串,则可以使用`==`运算符判断两个字符串是否相等,示例代码如下:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1 = "Hello";
string str2 = "world";
string str3 = "Hello";
if (str1 == str2) {
cout << "str1 and str2 are equal" << endl;
} else {
cout << "str1 and str2 are not equal" << endl;
}
if (str1 == str3) {
cout << "str1 and str3 are equal" << endl;
} else {
cout << "str1 and str3 are not equal" << endl;
}
return 0;
}
```
输出结果为:
```
str1 and str2 are not equal
str1 and str3 are equal
```
阅读全文