使用三路比较运算符比较两个字符串并输出结果 c++20代码
时间: 2023-12-29 17:02:26 浏览: 30
在C++20中,可以使用`<=>`运算符进行三向比较。比较两个字符串可以直接使用字符串比较运算符`==`、`!=`、`<`、`>`、`<=`、`>=`。以下是一个示例代码:
```c++
#include <iostream>
#include <string>
int main() {
std::string str1 = "hello";
std::string str2 = "world";
auto cmp = str1 <=> str2;
if (cmp == 0) {
std::cout << "str1 equals str2" << std::endl;
} else if (cmp < 0) {
std::cout << "str1 is less than str2" << std::endl;
} else {
std::cout << "str1 is greater than str2" << std::endl;
}
if (str1 == str2) {
std::cout << "str1 equals str2" << std::endl;
} else if (str1 < str2) {
std::cout << "str1 is less than str2" << std::endl;
} else {
std::cout << "str1 is greater than str2" << std::endl;
}
return 0;
}
```
输出结果为:
```
str1 is greater than str2
str1 is less than str2
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)
![](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)