Swapping pairs of characters in a String

Posted on

Problem

Question: Write a program to swap pairs of characters of a String. In
case of odd number of characters last character should remain
unchanged.

Examples:

Input: HI

Output: IH

Input: hello there

Output: ehll ohtree

My Code:

import java.util.*; 
class SwappedPairs
{
    static String swapPairs(String str)
    {
        int len = str.length(); 
        int n; //array's length
        if(len%2 == 0)
        {
            n = len;
        }
        else
        {
            n=len-1;
        }
        char []arr = new char[n];
        for(int i = 0; i< n; i++)
        {
            arr[i] = str.charAt(i); 
        }
        StringBuffer str1 = new StringBuffer(n); 
        for(int i = 0; i<=n-2; i= i+2)
        {
            char temp = arr[i]; 
            arr[i] = arr[i+1];
            arr[i+1] = temp; 
            str1 = str1.append(arr[i]).append(arr[i+1]);
        }

        if(len%2 != 0)
        {
             str1 .append(str.charAt(len-1));
        }
        str = str1.toString();
        return str;
    }

    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a string: ");
        String str = sc.nextLine(); 
        System.out.println(swapPairs(str));
    }
}

Any suggestion on how to improve it? (It gives the desired output)

Solution

It’s weird that you made both an array char[] arr and a StringBuffer str1. You’ve solved the problem twice, and discarded the arr result. And each solution is suboptimal. The array can be populated using String.toCharArray(). The StringBuffer is unnecessary, since you know the size of the buffer in advance, and you can eliminate the special case for odd-length strings if you don’t build a new string from scratch. In any case, since you don’t need thread safety, you would be better off with a StringBuilder instead of a StringBuffer.

public static String swapPairs(String str) {
    char[] arr = str.toCharArray();
    for (int i = 1; i < arr.length; i += 2) {
        char swap = arr[i];
        arr[i] = arr[i - 1];
        arr[i - 1] = swap;
    }
    return new String(arr);
}

Using a StringBuffer for building the new string is good,
but the variable name str1 is non-descriptive.

The computation of the required array length can be shortened
with the conditional operator:

int n = len % 2 == 0 ? len : len - 1;

Instead of swapping the array elements you can append them to the
string buffer in opposite order:

for (int i = 0; i <= n - 2; i = i + 2) {
    str1 = str1.append(arr[i+1]).append(arr[i]);
}

(and the re-assignment to str1 is not necessary).

And now one sees that the intermediate array is not needed at all:
You can append the swapped characters directly from the original string:

static String swapPairs(String str) {
    int len = str.length(); 
    StringBuffer swapped = new StringBuffer(len);
    for (int i = 0; i < len - 1 ; i += 2) {
        swapped.append(str.charAt(i + 1));
        swapped.append(str.charAt(i));
    }
    if (len % 2 != 0) {
        swapped.append(str.charAt(len - 1));
    }
    return swapped.toString();
}

Leave a Reply

Your email address will not be published. Required fields are marked *