Thursday, November 3, 2016

Swap two Strings without using third user defined variable

Problem
Given two string variables a and b, swap these variables without using temporary or third variable in Java. Use of library methods is allowed.

Solutions
We can use the String Split method and a separator to separating two string. We can also do this by using the substring method. Code below implement both the solutions.
 
public class SwapWithoutVar {
    public static void main(String[] args) {
        String a = "Hello";
        String b = "World";

        //Using String Split
        SwapWithSplit(a, b);

        //Using String Substring
        SwapWithSubString(a, b);

    }

    private static void SwapWithSubString(String a, String b) {
        System.out.println(String.format("Before Swap : a - %s, b - %s", a, b));
        b = a + b;
        a = b.substring( b.indexOf(a) + a.length());
        b = b.substring(0, b.indexOf(a));
        System.out.println(String.format("After Swap : a - %s, b - %s", a, b));
    }

    private static void SwapWithSplit(String a, String b) {
        System.out.println(String.format("Before Swap : a - %s, b - %s", a, b));
        b = b + "," + a;
        a = b;
        b = b.split(",")[1];
        a = a.split(",")[0];
        System.out.println(String.format("After Swap : a - %s, b - %s", a, b));
    }
}

Comments are welcome. Question source geeksforgeeks

No comments:

Post a Comment