How to swap two string variables in Java without using a third variable

你。 提交于 2019-12-02 21:36:10
Ankur Lathi

Do it like this without using a third variable:

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

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

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

// taken from this answer: https://stackoverflow.com/a/16826296/427413

String returnFirst(String x, String y) {
    return x;
}

String a = "one"
String b = "two"
a = returnFirst(b, b = a); // If this is confusing try reading as a=b; b=a;

This works because the Java language guarantees (Java Language Specification, Java SE 7 Edition, section 15.12.4.2) that all arguments are evaluated from left to right (unlike some other languages, where the order of evaluation is undefined), so the execution order is:

  1. The original value of b is evaluated in order to be passed as the first argument to the function
  2. The expression b = a is evaluated, and the result (the new value of b) is passed as the second argument to the function
  3. The function executes, returning the original value of b and ignoring its new value
  4. You assing the result to a
  5. Now the values have been swapped and you didn't need to declare temp. The parameter x works as temp, but it looks cleaner because you define the function once and you can use it everywhere.
Husman
String a="one";
String b="two";

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

This will work as long as your string doesn't contain the # character in them. Feel free to use any other character instead.

You could use a possible Unicode character, like "\u001E" instead of the #.

Couchcamote
public class SwapStringVariable {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String a = "test";
        String b = "paper";

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

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


    }

}
String str1 = "first";
String str2 = "second";

str1 = str2+str1;
str2 = str1.substring(str2.length(),str1.length());
str1 = str1.substring(0,(str1.length() - str2.length()));

System.out.println(str1);
System.out.println(str2);
String name = "george";
String name2 = "mark";
System.out.println(name+" "+name2);
System.out.println(name.substring(name.length()) + name2 +  " "+ name );

Here substring(); method returns empty string. hence , names can be appended.

commit

Here you go. Try this:

String a = "one";
String b = "two";
//String temp=null;
int i = a.length();
a += b;
b = a.substring(0, i);
a = a.substring(i, a.length());
System.out.println(a + " " + b);

Take any value in as string in a variable. It will be swap.

Praveen P Moolekandathil

The simplest way is given below:

String a = "one";
String b = "two";
System.out.println("Before swap: " a + " " + b);
int len = a.length();
a = a + b;
b = a.substring(0, len);
a = a.substring(len);
System.out.println("After swap: " a + " " + b);
armysheng
troy

Jj Tuibeo's solution works if you add replaceFirst() and use a regular expression:

a += b;
b = a.replaceFirst(b + "$", "");
a = a.replaceFirst("^" + b, "");

For String Method 1:

public class SwapWithoutThirdVar{  
public static void main (String args[]){    
 String s1 ="one";
 String s2 ="two";
 s1= s1+s2;
 s2 = s1.substring(0,(s1.length()-s2.length()));
 s1 = s1.substring(s2.length()); 
 System.out.println("s1 == "+ s1);
 System.out.println("s2 == "+ s2);

}
}

Method 2:

public class SwapWithoutThirdVar
{
public static void main (String[] args) throws java.lang.Exception
 {
 String s1 = "one";            
 String s2 ="two";          
 s1=s2+s1;
 s2=s1.replace(s2,"");
 s1=s1.replace(s2,"");         
 System.out.println("S1 : "+s1); 
 System.out.println("S2 : "+s2);
  }
}

For Integers

public class SwapWithoutThirdVar {

public static void main(String a[]){
    int x = 10;
    int y = 20;       
    x = x+y;
    y=x-y;
    x=x-y;
    System.out.println("After swap:");
    System.out.println("x value: "+x);
    System.out.println("y value: "+y);
}
}

You can do in this way.

public static void main(String[] args) {
        // TODO Auto-generated method stub

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

        System.out.println(a);
        System.out.println(b);

        a = a+b;
        b = "";

        System.out.println("*************");
         b = a.substring(0, 3);
         a = a.substring(3, 6);

         System.out.println(a);
         System.out.println(b);

    }

package com.core;

public class SwappingNoTemp {

public static void main(String[] args) {

    String a = "java";
    String b = "c";

    a = a + b;

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

    System.out.println("swapping is a.." + a);
    System.out.println("swapping  is b.." + b);

}

}

String a = "one";//creates "one" object on heap
String b = "two";// creates "two" object on heap
System.out.printf("a is %s , b is %s%n",a,b);
a = "two";// will not create new "two" object & now a is pointing to "two" object
b = "one";// will not create new "one" object & now b is pointing to "one" object
System.out.printf("a is %s , b is %s%n",a,b);
Jj Tuibeo

For strings:

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

a = a + b;
b = a.replace(b, "");
a = a.replace(b, "");
sandeep kumar sahoo
public class ex{
    public static void main(String[] args){

        String s1="abc";
        String s2="def";

        System.out.println(s1);
        System.out.println(s2);

        s3=s2.replaceAll(s1,s2=s1);

        System.out.println(s1);
        System.out.println(s2);

    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!