C++判断字符串是否相等
时间: 2023-11-15 18:56:23 浏览: 47
可以使用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
```
相关问题
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++ 中,可以使用字符串类 string 的 compare() 或者 == 运算符来比较两个字符串是否相等。
例如,可以使用以下代码判断两个字符串 str1 和 str2 是否相等:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1 = "hello";
string str2 = "world";
if (str1 == str2) {
cout << "str1 equals str2" << endl;
} else {
cout << "str1 does not equal str2" << endl;
}
return 0;
}
```
也可以使用 compare() 方法:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1 = "hello";
string str2 = "world";
if (str1.compare(str2) == 0) {
cout << "str1 equals str2" << endl;
} else {
cout << "str1 does not equal str2" << endl;
}
return 0;
}
```
以上两种方法都可以判断两个字符串是否相等。