Reversing the contents of a std::string
can be done easily using standard library functions. Here are a few methods to achieve this.
std::reverse
The std::reverse
algorithm from the <algorithm>
header is the simplest way to reverse a string. For example:
#include <iostream>
#include <string>
#include <algorithm>
int main(){
std::string Text{"Hello, World!"};
std::reverse(Text.begin(), Text.end());
std::cout << Text;
}
!dlroW ,olleH
You can also write a custom function to reverse a string if you need more control over the process. For example:
#include <iostream>
#include <string>
void ReverseString(std::string& str) {
size_t n = str.size();
for (size_t i = 0; i < n / 2; ++i) {
std::swap(str[i], str[n - i - 1]);
}
}
int main() {
std::string Text{"Hello, World!"};
ReverseString(Text);
std::cout << Text;
}
!dlroW ,olleH
You can use a stack to reverse a string, which might be useful in certain contexts, such as parsing algorithms. For example:
#include <iostream>
#include <string>
#include <stack>
int main() {
std::string Text{"Hello, World!"};
std::stack<char> Stack;
for (char c : Text) {
Stack.push(c);
}
std::string Reversed;
while (!Stack.empty()) {
Reversed += Stack.top();
Stack.pop();
}
std::cout << Reversed;
}
!dlroW ,olleH
If you prefer using iterators, you can construct a reversed string using reverse iterators. For example:
#include <iostream>
#include <string>
int main() {
std::string Text{"Hello, World!"};
std::string Reversed(
Text.rbegin(), Text.rend()
);
std::cout << Reversed;
}
!dlroW ,olleH
std::reverse
is the most efficient method for most use cases.By using these techniques, you can easily reverse the contents of a std::string
in C++.
Answers to questions are automatically generated and may not have been reviewed.
std::string
ObjectsA practical guide covering the most useful methods and operators for working with std::string
objects and their memory