Yes, C++ has a built-in function to reverse a string: std::reverse(), defined in the <algorithm> header. It works on any sequence container, including std::string, and reverses the elements in place. For example, std::reverse(str.begin(), str.end()); reverses the string str.
How std::reverse Works
std::reverse() takes two iterators (or pointers) that define a range: the first iterator points to the first element, and the second points to one past the last element. It swaps elements symmetrically from both ends toward the middle. The function is in-place, meaning it modifies the original string rather than creating a copy. Its time complexity is O(n), where n is the number of characters, and it uses constant extra space (O(1)).
Here is a minimal, complete example:
#include <iostream>
#include <string>
#include <algorithm>
int main() {
std::string s = "Hello";
std::reverse(s.begin(), s.end());
std::cout << s; // Output: olleH
return 0;
}
Note that std::reverse() works on any bidirectional iterator range, so you can also use it on arrays, std::vector, or even a substring of a string by passing appropriate iterators.
Alternative: std::string Constructor or Assign
If you need a new reversed string without modifying the original, you can use the std::string reverse iterators (rbegin() and rend()) in the constructor or the assign() method. This is not a separate function but a common idiom:
std::string original = "world";
std::string reversed(original.rbegin(), original.rend());
// reversed is "dlrow"
This creates a new string by copying characters in reverse order. It is equivalent to std::reverse in terms of result but does not change the original. If you want to keep the original and assign the reversed version to another existing string, use:
std::string target;
target.assign(original.rbegin(), original.rend());
When to Use std::reverse vs. Reverse Iterators
Choose std::reverse() when you want to modify the string in place, for example, when processing a string and then discarding the original order. Choose the reverse-iterator constructor or assign() when you need to preserve the original string and create a reversed copy. The copy approach is also useful when you need to pass a reversed string to a function without altering the caller’s data.
There is no performance difference for typical strings; both are O(n). However, the reverse-iterator constructor may allocate memory for the new string, whereas std::reverse() does not allocate.
Common Pitfalls and Misconceptions
One common mistake is forgetting to include <algorithm> when using std::reverse(). Without it, the code will not compile. Another pitfall is trying to reverse a string literal directly, e.g., std::reverse("hello", "hello" + 5); – this works because string literals decay to pointers, but it is safer to use a std::string.
A frequent misconception is that std::reverse() returns a new string. It does not; it returns void. If you try std::string s2 = std::reverse(s.begin(), s.end());, you will get a compile error. Always remember it modifies in place.
Another issue is reversing a substring. For instance, to reverse only the first three characters of a string, use:
std::string s = "abcdef";
std::reverse(s.begin(), s.begin() + 3);
// s becomes "cbadef"
Make sure the iterators are valid and that the range is not empty (if begin == end, nothing happens).
Performance and Memory Considerations
For very large strings, std::reverse() is efficient because it does not allocate extra memory. The reverse-iterator constructor, on the other hand, allocates memory for the new string, which could be significant if the string is large. If you are reversing a string repeatedly in a loop, consider reusing a buffer and using std::reverse() on that buffer to avoid repeated allocations.
If you need to reverse a string in-place but also keep the original, you can copy the original first and then reverse the copy. That is still O(n) memory, but it is a clear approach.
Comparison with Other Languages and C-Style Strings
In C, there is no built-in string reverse function; you would write a manual loop. In Python, you can use s[::-1] or reversed(s). In Java, new StringBuilder(s).reverse().toString(). C++’s std::reverse() is similar to Python’s list.reverse() in that it modifies in place, but it is generic and works on any container.
For C-style strings (null-terminated arrays of char), you cannot directly use std::reverse() because it expects a range, but you can pass pointers to the beginning and the end (excluding the null terminator). For example:
char cstr[] = "hello";
std::reverse(cstr, cstr + 5); // cstr becomes "olleh"
Be careful to exclude the null terminator, otherwise you would reverse the null into the middle of the string, causing undefined behavior.
Frequently Asked Questions
Is there a built-in function to reverse a string in C++?
Yes, the built-in function is std::reverse() from the <algorithm> header. It reverses the elements in a range in place. For a string, you call it with str.begin() and str.end().
Does std::reverse() return a new string?
No, std::reverse() returns void. It modifies the string in place. If you need a new reversed string, use the reverse-iterator constructor: std::string reversed(original.rbegin(), original.rend());.
How do I reverse a substring of a string?
Pass iterators that define the substring range. For example, to reverse characters from index 2 to 5 (inclusive), use std::reverse(str.begin() + 2, str.begin() + 6);. Remember the second iterator is one past the last character you want to reverse.
Can I use std::reverse() on a C-style string?
Yes, but you must pass pointers to the beginning and one past the last character (excluding the null terminator). For example, std::reverse(cstr, cstr + strlen(cstr));. Including the null terminator would corrupt the string.
What is the time complexity of reversing a string with std::reverse()?
It is O(n), where n is the number of characters. It performs about n/2 swaps, each taking constant time, so the total is linear.
Is there a difference between std::reverse and std::reverse_copy?
Yes. std::reverse_copy() copies the reversed elements to a destination range without modifying the original. It is defined in the same header and takes three iterators: first, last, and destination. It returns an iterator to the end of the destination range. Use it when you need a reversed copy without writing a loop.
Related
- Shortcut to Switch Between Windows (All OS)
- Generate Random Number HTML: JS & Math.random Code
- Google Sheets Percentage Increase Formula
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- How to Create Rules in Outlook to Sort Incoming EmailTo create an Outlook rule, choose the conditions a message must meet and the action Outlook should take,…
- Excel SUMIF for Text: Match and Join Text Values EasilyExcel has no SUMIF function that adds text strings, but in Microsoft 365 you can use TEXTJOIN with…
- COUNTIF Criteria Examples for ExcelIn Excel for Microsoft 365, COUNTIF counts cells in one range that meet one condition: enter the range…
- Excel F4: How to Lock Cell References in FormulasTo lock a cell reference in an Excel formula, edit the formula, place the cursor in or select…
- Excel XLOOKUP Next Match: How to Get the 2nd ResultTo get the next match with XLOOKUP in Excel, use the match_mode and search_mode arguments together with a…
- Excel Formula for Date Sequence: 4 Easy WaysThe simplest Excel formula for a date sequence is =A2+1 entered in cell A3, assuming A2 holds your…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.