C++判断两个字符串相等
时间: 2023-08-13 17:05:58 浏览: 51
在C++中,可以使用`==`运算符来判断两个字符串是否相等。例如:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1 = "hello";
string str2 = "world";
if(str1 == str2) {
cout << "str1 is equal to str2" << endl;
} else {
cout << "str1 is not equal to str2" << endl;
}
return 0;
}
```
输出结果为:
```
str1 is not equal to str2
```
相关问题
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;
}
```
以上两种方法都可以判断两个字符串是否相等。
C++怎么判断两个字符串相等
在C语言中,可以使用strcmp函数来判断两个字符串是否相等。strcmp函数的原型为:
```c
int strcmp(const char* string1, const char* string2);
```
该函数会比较两个字符串string1和string2,并返回一个整数值:
- 如果string1等于string2,返回0
- 如果string1小于string2,返回一个负数
- 如果string1大于string2,返回一个正数
因此,可以通过判断strcmp的返回值是否为0,来判断两个字符串是否相等。例如:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "hello";
char str2[] = "hello";
char str3[] = "world";
if (strcmp(str1, str2) == 0) {
printf("str1 and str2 are equal\n");
} else {
printf("str1 and str2 are not equal\n");
}
if (strcmp(str1, str3) == 0) {
printf("str1 and str3 are equal\n");
} else {
printf("str1 and str3 are not equal\n");
}
return 0;
}
```
输出结果为:
```
str1 and str2 are equal
str1 and str3 are not equal
```