4.5. Reversing a String

Problem

You want to reverse a string.

Solution

To reverse a string “in place,” without using a temporary string, use the reverse function template in the <algorithm> header:

std::reverse(s.begin(), s.end());

Discussion

reverse works simply enough: it modifies the range you give it such that it is in the opposite order that it was originally. It takes linear time.

In the event that you want to copy the string to another string, but backward, use reverse iterators, like this:

std::string s = "Los Angeles";
std::string rs;

rs.assign(s.rbegin(), s.rend());

rbegin and rend return reverse iterators. Reverse iterators behave as though they are looking at the sequence backward. rbegin returns an iterator that points to the last element, and rend returns an iterator that points to one before the first; this is exactly opposite of what begin and end do.

But do you need to reverse the string in the first place? With rbegin and rend, any member functions or algorithms that operate on iterator ranges can be used on the reverse version of the string. And if you want to search through the string, you can use rfind to do what find does but starting from the end of the string and moving backward. For large strings, or large numbers of strings, reversing can be expensive, so avoid it if you can.

Get C++ Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.