Switching Pairs

-1 Ashy - · September 5, 2014
Hey everyone. Right now I'm trying to write down a program where I can switch the pairs of 2 characters within a string. I want to make sure that every even pair isn't changed while every odd pair is. So if I have something like "AB CD EF GH" I want the result "AB DC EF HG"

Also, if there happens to be an odd number of characters within the string than the last character can stay just the way it is. Can anyone help me write this program? Thanks in advance.

Post a Reply


Oldest  Newest  Rating
0 Siddharth Isaiah · September 15, 2014
Hi Ashy,

you can solve this problem by -

splitting the string by white spaces and storing it in an array. You can then loop over this array that you just created and reverse the characters on every alternate array index.

heres the code:

String spaces= "AB CD EF GH";
        String revWord = "";
//splitting the string by white space
        String[] splitArray = spaces.split("\\s");

//looping over the newly created array
        for (int i = 1; i < splitArray.length; i += 1) { //looping by every other word
            if (splitArray.length() == 2) {
                char[] reverse = {splitArray.charAt(1), splitArray.charAt(0)};
                for (char c : reverse) { //exchanging letters
                    revWord += c;
                splitArray = revWord; // inserting reversed pair into place
                revWord = "";

//displaying the modified array
        for (String x : splitArray) {
            System.out.print(x + " ");
  • 1

Java / Android Development


Very popular language used to create desktop applications, website applets, and Android apps.

Bucky Roberts Administrator