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

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

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

    a += b;
    b = a.replaceFirst(b + "$", "");
    a = a.replaceFirst("^" + b, "");
    
    0 讨论(0)
  • 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);
    }
    }
    
    0 讨论(0)
  • 2021-02-02 13:02
    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);
    
    0 讨论(0)
  • 2021-02-02 13:03
    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.

    0 讨论(0)
  • 2021-02-02 13:07

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

    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.

    0 讨论(0)
提交回复
热议问题