string有reverse
时间: 2023-06-17 20:06:29 浏览: 87
是的,C++中的string类有reverse()函数,可以将字符串反转。例如:
```cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "hello world";
reverse(s.begin(), s.end()); // 反转字符串
cout << s << endl; // 输出结果:dlrow olleh
return 0;
}
```
需要注意的是,reverse()函数只能用于反转字符串,不能用于反转其他容器类型如vector等。如果需要反转其他容器类型,可以使用算法库中的reverse()函数。
相关问题
c++string有reverse
C++中的string类是标准库提供的一个字符串处理类,它提供了许多方便的方法来操作字符串,其中包括reverse(反转)字符串的功能。
要使用reverse函数,需要包含<string>头文件,并使用std命名空间。下面是一个示例代码:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
std::reverse(str.begin(), str.end());
std::cout << str << std::endl;
return 0;
}
```
在上面的代码中,我们首先创建了一个名为str的string对象,并将其初始化为"Hello, World!"。然后,我们使用std::reverse函数将字符串进行反转。最后,我们将反转后的字符串输出到控制台。
运行上述代码,输出结果为"!dlroW ,olleH",即原始字符串"Hello, World!"的反转形式。
string 的reverse
C++ 中字符串的反转可以使用 STL 库中的 reverse 函数:
```
#include <algorithm>
#include <string>
std::string str = "Hello, World!";
std::reverse(str.begin(), str.end());
```
也可以手动循环交换字符串的首尾字符:
```
#include <string>
std::string str = "Hello, World!";
int length = str.length();
for (int i = 0; i < length / 2; i++) {
std::swap(str[i], str[length - i - 1]);
}
```
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)