string reverse函数
时间: 2024-05-16 22:09:27 浏览: 236
string reverse函数是一个用于将字符串反转的函数。它可以将一个字符串中的字符顺序颠倒过来,使得原来在前面的字符现在在后面,原来在后面的字符现在在前面。
实现string reverse函数的一种常见方法是使用两个指针,一个指向字符串的开头,另一个指向字符串的末尾。然后,交换这两个指针所指向的字符,并向中间移动指针,直到两个指针相遇为止。
以下是一个示例实现:
```cpp
#include <iostream>
#include <string>
std::string reverseString(const std::string& str) {
std::string reversedStr = str int start = 0;
int end = reversedStr.length() - 1;
while (start < end) {
std::swap(reversedStr[start], reversedStr[end]);
start++;
end--;
}
return reversedStr;
}
int main() {
std::string str = "Hello, World!";
std::string reversedStr = reverseString(str);
std::cout << "Reversed string: " << reversedStr << std::endl;
return 0;
}
```
运行上述代码,输出结果为:
```
Reversed string: !dlroW ,olleH
```
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)