Reversing a String


You want to reverse a string.


To reverse a string "in place," without using a temporary string, use the reverse function template in the header:

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



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.

C++ Cookbook
Secure Programming Cookbook for C and C++: Recipes for Cryptography, Authentication, Input Validation & More
ISBN: 0596003943
EAN: 2147483647
Year: 2006
Pages: 241
Simiral book on Amazon © 2008-2017.
If you may any questions please contact us: