How to implement string reversal in C++?
In C++, the following methods can be used to reverse a string:
- By using a loop: you can employ two pointers, one pointing to the beginning of the string and one pointing to the end. Then, swap the characters pointed to by the two pointers, and move the pointers towards the middle until they meet. An example code is shown below:
#include <iostream>
#include <string>
void reverseString(std::string& str) {
int left = 0;
int right = str.length() - 1;
while (left < right) {
std::swap(str[left], str[right]);
left++;
right--;
}
}
int main() {
std::string str = "Hello World";
reverseString(str);
std::cout << str << std::endl; // 输出 "dlroW olleH"
return 0;
}
- By using recursion, you can split a string into a character and the remaining substring, then recursively reverse the remaining substring and place the character at the end. Here is an example code:
#include <iostream>
#include <string>
std::string reverseString(const std::string& str) {
if (str.length() <= 1) {
return str;
}
return reverseString(str.substr(1)) + str[0];
}
int main() {
std::string str = "Hello World";
str = reverseString(str);
std::cout << str << std::endl; // 输出 "dlroW olleH"
return 0;
}
Both reversing a string can be achieved through either iteration or recursion. Depending on specific requirements and the length of the string, choose the appropriate method to implement it.