不用第3个变量,2个字符串
方法1:
String begin = "2012-06-01";
String end = "2012-06-30";
begin = begin + end;
end = begin.substring(10);//end ="2012-06-01"
begin = begin.substring(0,10);//begin = "2012-06-30"
用String java.lang.String.substring(int beginIndex, intendIndex);
来截取字符串来达到互换的目的
- public void method1(){
- String a = "字符串a" ;
- String b = "字符串b" ;
- a = a + b;
- b = a.substring(0,(a.length()-b.length()));
- a = a.substring(a.length()-b.length(),a.length());//主要此时b.length()时转换前a的长度
- System.out.println("a:"+a);
- System.out.println("b:"+b);
- }
方法二:
有运算符的优先级在里面。
先执行(b=a)把a的值赋b 然后repalceAll(b,"")把值致为""。最后就得到 a=b+"";
- public void method2(){
- String a = "字符串a" ;
- String b = "字符串b" ;
- a = b + (b = a).replaceAll(b, "") ;
- System.out.println("a:"+a);
- System.out.println("b:"+b);
- }
不用第3个变量,2个数值型值交换
方法1:(用加减:(数大的时候会溢出)
)
int e = 1;
int f = 3;
e = e + f; //e = 4
f = e - f; //f = 1
e = e - f; //e = 3
方法2:(用异或:(推荐))
a^=b;
b^=a;
a^=b;
/**
*<不用第三个变量,交换两个变量的值>
*/
publicstaticvoid main(String[] args)
{
//方法一 精简,一行代码搞定
int x = 3, y = 7, t = 123;
System.out.printf("x = %d, y = %d\n", x, y);
x = y + 0 * (y = x);
System.out.printf("x = %d, y = %d\n", x, y);
//方法二 简单明了
int p = 4, q = 9;
System.out.printf("p = %d, q = %d\n", p, q);
p = p + q; //7
q = p - q; // 7-5=2 q == p
p = p - q; //7-2
System.out.printf("p = %d, q = %d\n", p, q);
//方法三 兼容,支持Integer.MAXVALUE的+操纵
int a = 2, b = 5;
System.out.printf("a = %d, b = %d\n", a, b);
a ^= b;
b ^= a;
a ^= b;
System.out.printf("a = %d, b = %d\n", a, b);
//方法四 字符串数组
String s1 = "111", s2 = "222";
System.out.printf("s1 = %s, s2 = %s\n", s1, s2);
s1 = s1 + "," + s2;
s2 = s1;
s1 = s1.split(",")[1];
s2 = s2.split(",")[0];
System.out.printf("s1 = %s, s2 = %s\n", s1, s2);
//方法五 字符串表达式(类似方法一)
String str1 = "aaa", str2 = "bbb";
System.out.printf("str1 = %s, str2 = %s\n", str1, str2);
str1 = str2 + ((str2 = str1) == "" ? "" : "");
System.out.printf("str1 = %s, str2 = %s\n", str1, str2);
}