Use std::reverse from the <algorithm> header to reverse a mutable C++ string in place: call std::reverse(text.begin(), text.end());. It works with std::string and other mutable containers that provide suitable iterators; it changes the original string rather than making a reversed copy.
The Standard C++ Way to Reverse a String
The standard library’s std::reverse algorithm is the usual choice. It takes two iterators identifying a half-open range: the first iterator points to the first element to include, and the second points just past the last element. For an entire string, begin() and end() specify exactly that range.
#include <algorithm>
#include <string>
std::string text = "hello";
std::reverse(text.begin(), text.end());
// text is now "olleh"
Include <algorithm> for the algorithm and <string> for std::string. The call itself returns no reversed string: it rearranges the elements in the range. If other code still needs the original order, make a copy first or use a separate reversed-result technique.
There is no standard std::string::reverse() member function. A common mix-up is to look for a method such as text.reverse(); the standard operation is the free algorithm std::reverse, called with iterators.
A Complete Program
This small program reads a line, reverses it, and prints the result. std::getline is used instead of formatted input so spaces in the line are preserved.
#include <algorithm>
#include <iostream>
#include <string>
int main() {
std::string text;
std::getline(std::cin, text);
std::reverse(text.begin(), text.end());
std::cout << text << '\n';
}
If the input is strawberry pie, the output is eip yrrebwarts. For a one-word input, std::cin >> text is another option, but it stops reading at whitespace. Reversing an empty string is also valid: its begin and end iterators are equal, so the algorithm has no elements to change.
How std::reverse Works
Conceptually, the algorithm swaps the first element with the last, then the second with the second-to-last, continuing toward the middle. When the iterators meet or cross, the operation is done. The elements in the middle of an odd-length string need no swap.
The algorithm requires bidirectional iterators, which can move both forward and backward. std::string iterators satisfy that requirement, so no conversion to an array or special string routine is needed. Because the endpoints describe a half-open range, the final element is end() - 1, not end(). Passing end() as the second argument is correct; trying to dereference it is not.
Reversal changes character positions, not the characters themselves. For example, reversing "abcde" swaps the outer pairs and leaves c in the middle. This operation is a permutation: it does not add or remove characters, and the string’s size remains the same.
Reverse in Place or Create a Copy?
In-place reversal is concise and avoids allocating another string for the result. Choose it when the original order is no longer needed. If the original must remain intact, copy the string and reverse the copy:
#include <algorithm>
#include <string>
std::string original = "drawer";
std::string reversed = original;
std::reverse(reversed.begin(), reversed.end());
// original is "drawer"; reversed is "reward"
Copying uses additional memory proportional to the string’s length, while in-place reversal works within the existing string storage. The copy is often the clearest option when both versions are needed. Keep in mind that later edits to one string do not automatically update the other; they are separate string objects.
A reversed copy can also be constructed with reverse iterators:
std::string reversed(original.rbegin(), original.rend());
rbegin() and rend() traverse the characters in reverse order, and the string constructor copies that sequence into a new string. This is a useful compact expression, while the copy-then-reverse form makes the mutation step more explicit.
Reversing Part of a String
std::reverse can operate on any valid subrange, not only the whole string. For example, to reverse the characters from index 1 through index 3 in "abcdef", use the iterator range from begin() + 1 to begin() + 4. The second iterator is one past the final included character.
std::string text = "abcdef";
std::reverse(text.begin() + 1, text.begin() + 4);
// text is "adcbef"
Before forming iterator offsets from indexes, make sure the requested range is within the string’s size. An out-of-range iterator is not a safe way to express an empty or oversized range and can cause undefined behavior. For an empty subrange at a valid position, pass the same iterator as both endpoints.
Complexity and When to Choose It
std::reverse performs a number of swaps proportional to the range length, commonly described as linear time, or O(n). It uses constant extra algorithm storage: it swaps elements in place rather than building a second sequence. A separate copied result, of course, requires storage for that copy.
- Use
std::reverse(text.begin(), text.end())when you want to modify a mutable string. - Use a copied string plus
std::reversewhen you need to preserve the original and want the steps to be obvious. - Use reverse iterators to construct a reversed copy in one expression.
- For a non-owning reverse traversal, consider reverse iterators or a suitable view rather than changing the string.
For ordinary byte-oriented string work, there is usually no speed or clarity benefit to writing a manual swap loop. The standard algorithm communicates the intent directly and avoids common index-boundary mistakes. A manual loop can still be appropriate when the reversal is only one part of a larger specialized operation, but it should be justified by that wider requirement.
Important Unicode and UTF-8 Caveat
Reversing a std::string reverses its stored char elements. It does not necessarily reverse what a person understands as the visible characters. In UTF-8, one Unicode code point can occupy multiple bytes. Reversing those bytes separately can break the encoding and produce invalid text.
Even reversing by Unicode code point may not preserve user-perceived characters. Some displayed symbols consist of multiple code points, such as a base letter followed by a combining accent, or an emoji sequence joined from several components. A byte-level algorithm cannot identify those grapheme clusters or determine their display behavior.
If the string contains only ASCII characters, reversing its bytes gives the expected character order. If it may contain general UTF-8 text, use a Unicode-aware library or a carefully designed decoding and grapheme-segmentation approach. Simply converting each byte to another character type does not solve Unicode segmentation.
Common Errors and Misconceptions
- Forgetting the header: include
<algorithm>;std::reverseis not declared by<string>alone. - Calling it as a member: write
std::reverse(text.begin(), text.end()), nottext.reverse(). - Trying to modify a const string: a
const std::stringprovides read-only iterators, so it cannot be reversed in place. Copy it into a non-const string first. - Using the wrong endpoint:
end()is the one-past-the-end iterator and is intended as the range endpoint; do not dereference it. - Expecting a returned string: the algorithm mutates its range and does not return a new string.
- Assuming UTF-8 bytes are characters: byte reversal is safe as text reversal only for suitable single-byte content such as ASCII.
Also note that a string literal itself is not a mutable std::string. Create a std::string object before passing its iterators to std::reverse. Modifying a string literal through a pointer is not a valid substitute.
Alternatives: Reverse Iterators and Ranges
Reverse iterators are useful when you want to read or copy characters in reverse order without changing the source. For example, a range-based loop can traverse a string backward:
for (auto it = text.rbegin(); it != text.rend(); ++it) {
std::cout << *it;
}
This prints characters in reverse order but leaves text unchanged. It is not the same as calling std::reverse, which changes the sequence itself. Reverse iteration is also useful for algorithms or checks that need to inspect a string from its end.
C++20 adds ranges facilities, including std::ranges::reverse, which can be used with a suitable range such as a mutable string. It is another standard-library spelling for an in-place reversal, not a Unicode-aware operation and not a function that returns a reversed copy. For code targeting older language standards, the classic std::reverse algorithm remains broadly available and is usually the simplest choice.
Frequently Asked Questions
Does C++ have a built-in string reverse function?
No standard std::string::reverse() member exists. Use the standard algorithm std::reverse from <algorithm>, passing the string’s beginning and ending iterators.
How do I reverse a string without changing the original?
Copy it first, then reverse the copy with std::reverse(copy.begin(), copy.end()). Alternatively, construct a new string from the original’s rbegin() and rend() iterators.
Can std::reverse be used on an empty string?
Yes. An empty string has an empty iterator range, and reversing that range does nothing. No special case is required.
What is the time complexity of reversing a C++ string?
It is O(n), where n is the number of elements in the range. The algorithm swaps elements from the ends toward the middle and does not allocate a second string for an in-place operation.
Does reversing std::string work correctly with Unicode?
Not in general. It reverses stored bytes, which can split UTF-8 code points and disrupt multi-code-point grapheme clusters. Use a Unicode-aware solution when text may contain characters beyond simple ASCII.
Related
- Java split() Method: Split Strings with Regex and Limits
- Balance C/D in Accounting: Meaning and Examples
- A/B Split Testing: Meaning, Method, and Common Mistakes
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Excel Not Letting You Put a 0 in Front of a Number?Excel removes a leading zero when it interprets what you type as a number. To keep the zero…
- How to Hide a Column in Excel and Unhide It EasilyYes. In Excel for Microsoft 365 on Windows, select the column letter, right-click it, and choose Hide. To…
- Excel Convert German Number Format to English NumbersYes. To convert German-formatted text such as 1.234,56 into a real Excel number, put the text in A2…
- How to Add a Drop-Down List to an Excel Column Step by StepTo add a drop-down list to an Excel column, select the cells that should contain it, then choose…
- Advanced Filter in Google Sheets: Methods and ExamplesGoogle Sheets does not have a single command named “Advanced Filter” like Microsoft Excel. To filter a table…
- Excel: Hide Duplicates Based on One Column in a ListTo hide entire rows when a value repeats in one column, add a helper column, mark the first…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.