Swapping Pairs of Characters in a String in Java

Given string str, the task is to write a Java program to swap the pairs of characters of a string. If the string contains an odd number of characters then the last character remains as it is.

Examples:

Input: str = “Java”

Output: aJva

Explanation: The given string contains even number of characters. Therefore, we swap every pair of characters.



Input: str = “GeeksForGeeks”

Output: eGkeFsroeGkes

Explanation: The given string contains odd number of characters. Therefore, we swap every pair of characters and last character remains as it is.

1. Using String.toCharArray() Method

  1. Get the string to swap a pair of characters.
  2. Check if the string is null or empty then return the string.
  3. Converting the given string into a character array.
  4. Traverse the character array and swap the characters.
  5. Now, print the result.

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to swap pair
// of characters of a string
  
class GFG {
  
    // Function to swap pair of
    // characters of a string
    public static String swapPair(String str)
    {
  
        // Checking if string is null
        // or empty then return str
        if (str == null || str.isEmpty())
            return str;
  
        // Converting the given string
        // into a character array
        char[] ch = str.toCharArray();
  
        // Traverse the character array
        for (int i = 0; i < ch.length - 1; i += 2) {
  
            // Swapping the characters
            char temp = ch[i];
            ch[i] = ch[i + 1];
            ch[i + 1] = temp;
        }
  
        // Converting the result into a
        // string and return
        return new String(ch);
    }
  
    // Driver Code
    public static void main(String args[])
    {
  
        // Given String str
        String str = "GeeksForGeeks";
  
        // Print the result
        System.out.println(swapPair(str));
    }
}

chevron_right


Output

eGkeFsroeGkes


2. Using StringBuffer.append() Method

  1. Get the string to swap a pair of characters.
  2. Check if the string is null or empty then return the string.
  3. Creating a StringBuffer object with a length of the string passed as a parameter.
  4. Traverse the string and append the characters in the StringBuffer object in reverse order.
  5. Check if the string contains an odd number of characters then append the last character into the StringBuffer object.
  6. Now, print the result.

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to swap pair
// of characters of a string
  
class GFG {
  
    // Function to swap pair of
    // characters of a string
    public static String swapPairs(String str)
    {
  
        // Checking if string is null
        // or empty then return str
        if (str == null || str.isEmpty())
            return str;
  
        int len = str.length();
  
        // Creating a StringBuffer object with
        // length of the string passed as a parameter
        StringBuffer sb = new StringBuffer(len);
  
        // Traverse the string and append
        // the character in the StringBuffer
        // object in reverse order
        for (int i = 0; i < len - 1; i += 2) {
            sb.append(str.charAt(i + 1));
            sb.append(str.charAt(i));
        }
  
        // Checking if the string has
        // odd number of characters
        // then append the last character
        // into StringBuffer object
        if (len % 2 != 0) {
            sb.append(str.charAt(len - 1));
        }
  
        // Converting the StringBuffer
        // into the string and return
        return sb.toString();
    }
  
    // Driver Code
    public static void main(String args[])
    {
  
        // Given String str
        String str = "GeeksForGeeks";
  
        // Print the result
        System.out.println(swapPairs(str));
    }
}

chevron_right


Output

eGkeFsroeGkes


Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

External Technical Content Reviewer at GeeksforGeeks

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.