stl string reverse
时间: 2023-08-14 19:12:01 浏览: 67
使用STL中的string类实现字符串反转,可以使用`std::reverse`函数。下面是一个示例代码:
```cpp
#include <iostream>
#include <algorithm>
#include <string>
int main() {
std::string str = "Hello, world!";
std::reverse(str.begin(), str.end());
std::cout << str << std::endl;
return 0;
}
```
这段代码会将字符串`"Hello, world!"`反转为`"!dlrow ,olleH"`并输出。在这个示例中,我们使用了`std::reverse`函数来反转字符串中的字符。注意要包含`<algorithm>`和`<string>`头文件。
相关问题
string reverse的用法
string reverse()是一个C++ STL函数,它可以用于反转字符串。它在<algorithm>头文件中定义,可以像下面这样使用:
```c++
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
string str = "Hello World";
reverse(str.begin(), str.end());
cout << str << endl;
return 0;
}
```
这个程序将输出"dlroW olleH",因为它使用了reverse函数将字符串反转了。str.begin()表示字符串的第一个元素,str.end()表示字符串的最后一个元素的下一个元素,因此reverse(str.begin(), str.end())将str中的字符反转了。
c++ 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]);
}
```
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)