Friday 20 December 2013

Swapping two Strings without using temporary variable.

We saw swapping two numbers without using temporary or third variable(here). Now lets see how can we swap two Strings without using any extra variable.

/**
 * Created with IntelliJ IDEA.
 * User: aniket
 * Date: 20/12/13
 * Time: 8:49 PM
 */
public class StringSwapper {

    public static void main(String args[]){

        String a="one";
        String b="two";

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

        System.out.println("a = "+a);
        System.out.println("b = "+b);

    }


}



Output : 
a = two
b = one


Smarter Way

There is another swart way to do this - use a Special character to concatenate Strings and them split them to swap.

String a="one";
String b="two";
a = a.concat("#" + b);
b = a.split("#")[0];
a = a.split("#")[1];

But the problem with this approach is that you must take care that that the special character you use should not be part of the String

No comments:

Post a Comment

t> UA-39527780-1 back to top