Lichtamberg Lichtamberg - 2 months ago 6
C++ Question

How to reverse string pairwise

I'm an absolute newbie in C++, so I hope you can help me out.

I want to reverse a string with keeping pairwise order, here is an example:

ABCDEFGHIJ
=> IJGHEFCDAB

# or another example

0123456789
=> 8967452301


Could you tell me how to do this? Learning C++ is quite hard :) Thanks!

Edit: The strings are always HEX-codes (read from NFC chips), so I am sure that the size is always even.

Answer
#include <iostream>
#include <string>
#include <algorithm>

int main() {

    std::string s = "ABCDEFGH";

    std::reverse(s.begin(), s.end());
    for ( std::string::iterator it = s.begin(); it != s.end(); it += 2 )
        std::swap(*it, *(it+1));

    std::cout << s << std::endl;

    return 0;
}

EDIT

A more general solution that can be used with a different size of characters groups.

#include <iostream>
#include <string>
#include <algorithm>
#include <cassert>

int main() {

    std::string s = "ABCDEFGHI";

    const size_t GROUP_SIZE = 3;
    assert(s.size() % GROUP_SIZE == 0);
    std::reverse(s.begin(), s.end());
    for ( std::string::iterator it = s.begin(); it != s.end(); ) {
        std::string::iterator it2 = it;
        std::advance(it2, GROUP_SIZE);
        std::reverse(it, it2);
        it = it2;
    }
    std::cout << s << std::endl;

    return 0;
}
Comments