Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reversing a string in C++ using a reverse iterator?

I have the following code and I just can't seem to figure out a way to get the strings reversed here:

stringstream convert;
string y="";
string z="";
convert << x;
string::reverse_iterator rit;
y=convert.str();
int j=0;
for (rit = y.rbegin(); rit < y.rend(); rit++){
    z[j] = *rit;
    j++;
}

Can someone help me out with this? Thanks!

like image 551
HunderingThooves Avatar asked Aug 26 '11 01:08

HunderingThooves


1 Answers

z.assign(y.rbegin(), y.rend());

Or you can do it upon construction:

std::string z(y.rbegin(), y.rend());

If you want to modify a string in place, use std::reverse:

std::reverse(y.begin(), y.end());
like image 158
Benjamin Lindley Avatar answered Sep 21 '22 15:09

Benjamin Lindley