Reversing a std::string
is a common operation that can be accomplished efficiently using the standard library. Here's a look at a few methods, starting with the most straightforward and efficient:
#include <iostream>
#include <string>
#include <algorithm>
std::string reverse_string(std::string str) {
std::reverse(str.begin(), str.end());
return str;
}
int main() {
std::string text{"Hello, World!"};
std::cout << "Original: " << text << '\n';
std::cout << "Reversed: "
<< reverse_string(text) << '\n';
// In-place reversal
std::reverse(text.begin(), text.end());
std::cout << "Reversed in-place: "
<< text << '\n';
}
Original: Hello, World!
Reversed: !dlroW ,olleH
Reversed in-place: !dlroW ,olleH
The std::reverse()
function from the <algorithm>
header is the most efficient way to reverse a std::string
. It works in-place, modifying the original string, and has a time complexity of , where is the length of the string.
If you need to preserve the original string, you can create a copy first:
std::string reverse_string(const std::string& str) {
std::string reversed{str};
std::reverse(reversed.begin(), reversed.end());
return reversed;
}
For educational purposes, here's how you might implement string reversal manually:
std::string manual_reverse(
const std::string& str
) {
std::string reversed;
// Preallocate space
reversed.reserve(str.length());
for (
auto it = str.rbegin();
it != str.rend();
++it
) {
reversed.push_back(*it);
}
return reversed;
}
This manual method is less efficient than std::reverse()
but demonstrates the concept clearly.
For Unicode strings, simple reversal might not work correctly due to multi-byte characters and combining characters. In such cases, you'd need a more sophisticated approach or a Unicode-aware library.
Remember, when working with std::string
, it's often more efficient to modify the string in-place rather than creating a new string for each operation. The in-place reversal using std::reverse()
is typically the most efficient method for reversing a string in C++.
Answers to questions are automatically generated and may not have been reviewed.
std::string
ClassA detailed guide to std::string
, covering the most essential methods and operators