Swapping first and last Characters

Jan 18, 2012 at 7:53pm
Is there any way to swap first and last characters? If I had a string called hello, would it be possible to make it "oellh" just by swapping the first and last characters?
Jan 18, 2012 at 8:06pm
Swap can be done with swap(), the first character is the one at begin() and the last is the one at rbegin():

1
2
3
4
5
6
7
8
9
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
    std::string s = "hello";
    std::iter_swap(s.begin(), s.rbegin());
    std::cout << s << '\n';
}

demo: http://ideone.com/BvVg2
Last edited on Jan 18, 2012 at 8:07pm
Topic archived. No new replies allowed.