Swap two string without using third variable.

Write a program to swap two String without using third variable.

Example:

Input:  a="raman", b="rohan"
Output: a="rohan", b="raman"

Approach

Java

public class SwapStringWithoutVa {
    public static void main(String[] args) {

        String a = "raman";
        String b = "rohan";

        System.out.println("Before swap: " + a + " " + b);

        a = a + b;
        b = a.substring(0a.length() - b.length());
        a = a.substring(b.length());

        System.out.println("After : " + a + " " + b);

    }
}


No comments:

Post a Comment