C++string比较是否相同
时间: 2023-08-04 10:19:42 浏览: 91
C string深入详解2.0版_C++_string_
你可以使用C++中的`std::string`类提供的`compare()`函数进行字符串比较,该函数会返回一个整数,表示两个字符串的比较结果。如果返回值为0,则表示两个字符串相同。下面是一个示例代码:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str1 = "hello";
std::string str2 = "world";
std::string str3 = "hello";
int result1 = str1.compare(str2);
int result2 = str1.compare(str3);
if (result1 == 0) {
std::cout << "str1 is equal to str2" << std::endl;
} else {
std::cout << "str1 is not equal to str2" << std::endl;
}
if (result2 == 0) {
std::cout << "str1 is equal to str3" << std::endl;
} else {
std::cout << "str1 is not equal to str3" << std::endl;
}
return 0;
}
```
输出结果:
```
str1 is not equal to str2
str1 is equal to str3
```
阅读全文