How to swap two string variables in Java without u

2020-05-20 06:28发布

问题:

How do I swap two string variables in Java without using a third variable, i.e. the temp variable?

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

But here there is a third variable. We need to eliminate the use of the third variable.

回答1:

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);


回答2:

// 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.


回答3:

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 #.



回答4:

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);


    }

}


回答5:

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);


回答6:

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);


回答7:

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.



回答8:

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.



回答9:

  • Actually, the code in your question did not swap String a,b.

    You should see this issue: Swap two strings in Java, by passing them to a utility function, but without returning objects or using wrapper classes

  • And Java is passing by value: Is Java "pass-by-reference" or "pass-by-value"?



回答10:

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

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


回答11:

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);
}
}


回答12:

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);

    }


回答13:

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);

}

}



回答14:

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);


回答15:

You can also do this by using a temp variable but in a different way:

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

temp=a.concat(b);
b=temp.substring(0,a.length());
a=temp.substring(a.length(),temp.length());

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


回答16:

For strings:

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

a = a + b;
b = a.replace(b, "");
a = a.replace(b, "");


回答17:

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);

    }
}


标签: java string swap