在Java中,如何交换两个字符串变量而不使用第三个变量,即temp变量?
String a = "one"
String b = "two"
String temp = null;
temp = a;
a = b;
b = temp;
但是在这里有第三个变量,我们需要消除第三个变量的使用。
在Java中,如何交换两个字符串变量而不使用第三个变量,即temp变量?
String a = "one"
String b = "two"
String temp = null;
temp = a;
a = b;
b = temp;
但是在这里有第三个变量,我们需要消除第三个变量的使用。
请看这里。试试这个:
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);
Jj Tuibeo的解决方案可以工作,如果你添加replaceFirst()并使用正则表达式:
a += b;
b = a.replaceFirst(b + "$", "");
a = a.replaceFirst("^" + b, "");
b=".*"
。 - user3458String 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);
实际上,您问题中的代码没有交换字符串a和b。
您应该查看这个问题: 在Java中交换两个字符串,通过将它们传递给实用函数,但不返回对象或使用包装类
而且Java是按值传递的: Java是“传值”还是“传引用”?
你也可以使用一个临时变量以不同的方式完成这个操作:
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);
使用多维赋值进行交换:
var a = "one";
var b = "two";
console.log("a =",a);
console.log("b =",b);
a = [b, b = a][0];
console.log("after swap a =",a);
console.log("after swap b =",b);
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);
}
}
对于字符串:
String a = "one"
String b = "two"
a = a + b;
b = a.replace(b, "");
a = a.replace(b, "");