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.
Output :
a = two
b = one
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | /** * 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.
1 2 3 4 5 | String a= "one" ; String b= "two" ; a = a.concat( "#" + b); b = a.split( "#" )[ 0 ]; a = a.split( "#" )[ 1 ]; |
No comments:
Post a Comment