String对象每次拼接都会在常量池中新建一个String对象
通过使用StringBuilder可以解决
StringBuilder的定义,append方法的链式编程使用
package _2;
public class _127 {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
/*StringBuilder sb2=sb.append("hello");
System.out.println("sb:"+sb);
System.out.println("sb2:"+sb2);
System.out.println(sb==sb2);*/
/*sb.append("hello ");
sb.append("world ");
sb.append("java");
sb.append(100);
System.out.println(sb);
*/
//链式编程
sb.append("hello ").append("world ").append("java").append(100);
System.out.println(sb);
sb.reverse();
System.out.println(sb);
}
}
String与StringBuilder相互转换
package _2;
public class _130 {
public static void main(String[] args) {
StringBuilder sb=new StringBuilder();
sb.append("hello");
/*
StringBuilder通过sb.toString()转化成String类型,并赋值给String s
*/
String s=sb.toString();
System.out.println(s);
/*
String s通过StringBuilder(s)转化成StringBuilder类型,并赋值给新定义的sb2
*/
StringBuilder sb2=new StringBuilder(s);
System.out.println(sb);
//储存位置不同
System.out.println(sb==sb2);
}
}
字符串拼接升级版
package _2;
public class _131 {
public static void main(String[] args) {
int[] a = {1, 2, 3, 4, 5, 6};
String b = pj(a);
System.out.println(b);
}
public static String pj(int[] a) {
StringBuilder sb = new StringBuilder("{");
for (int i = 0; i < a.length; i++) {
sb.append(a[i]);
if (i < a.length - 1) {
sb.append(",");
} else {
sb.append("}");
}
}
String q = sb.toString();
return q;
}
}
//字符串拼接升级版
字符串反转升级版
package _2;
import java.util.Scanner;
public class _132 {
public static void main(String[] args) {
System.out.println("请输入字符串");
Scanner sc=new Scanner(System.in);
String s=sc.nextLine();
String a=fz(s);
System.out.println(a);
}
public static String fz(String a){
StringBuilder sb=new StringBuilder(a);
sb.reverse();
String b=sb.toString();
return b;
}
}
//字符串反转升级版