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

后端 未结 18 748
梦谈多话
梦谈多话 2021-02-02 12:30

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         


        
相关标签:
18条回答
  • 2021-02-02 13:12
    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 #.

    0 讨论(0)
  • 2021-02-02 13:13
    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);
    
    
        }
    
    }
    
    0 讨论(0)
  • 2021-02-02 13:15

    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);
    
    0 讨论(0)
  • 2021-02-02 13:16
    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);
    
    0 讨论(0)
  • 2021-02-02 13:17

    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);
    
        }
    
    0 讨论(0)
  • 2021-02-02 13:17

    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);
    
    0 讨论(0)
提交回复
热议问题