c++比较字符串是否相等
时间: 2023-08-20 14:25:17 浏览: 51
在 C++ 中比较字符串是否相等,可以使用字符串类的 compare() 函数或者直接使用运算符 "=="。例如:
```
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1 = "hello";
string str2 = "world";
// 使用 compare() 函数比较字符串是否相等
if (str1.compare(str2) == 0) {
cout << "str1 and str2 are equal" << endl;
} else {
cout << "str1 and str2 are not equal" << endl;
}
// 使用运算符 "==" 比较字符串是否相等
if (str1 == str2) {
cout << "str1 and str2 are equal" << endl;
} else {
cout << "str1 and str2 are not equal" << endl;
}
return 0;
}
```
输出结果:
```
str1 and str2 are not equal
str1 and str2 are not equal
```
相关问题
c++判断字符串是否相等
在C语言中,要判断两个字符串是否相等,可以使用strcmp函数进行比较。strcmp函数会逐个比较两个字符串的字符,直到出现不同的字符或遇到字符串结束符'\0'。如果两个字符串相等,strcmp函数返回0;如果不相等,返回非0值。
示例代码如下:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "hello";
char str2[] = "world";
if (strcmp(str1, str2) == 0) {
printf("两个字符串相等\n");
} else {
printf("两个字符串不相等\n");
}
return 0;
}
```
输出结果为:"两个字符串不相等"
C++判断字符串是否相等
可以使用C++中的字符串比较函数`strcmp()`来判断两个字符串是否相等。如果返回值为0,则表示两个字符串相等,否则不相等。
示例代码:
```c++
#include <iostream>
#include <cstring>
using namespace std;
int main() {
string str1 = "hello";
string str2 = "world";
string str3 = "hello";
if (strcmp(str1.c_str(), str2.c_str()) == 0) {
cout << "str1 and str2 are equal" << endl;
} else {
cout << "str1 and str2 are not equal" << endl;
}
if (strcmp(str1.c_str(), str3.c_str()) == 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
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)