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

后端 未结 18 939
梦谈多话
梦谈多话 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:00

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

提交回复
热议问题