1、StringBuilder
String s = "";
for (int i=0;i<100;i++){
s = s + "," + i;
}
/*每次拼接字符串都会丢掉旧的字符串,造成浪费内存;
为了高效拼接字符串,java标准库提供了StringBuilder,
它是一个可变对象,可以与存放缓冲区,增加字符时,不会创建新的临时对象
*/
public class Playing{
public static void main(String[] args) {
StringBuilder p = new StringBuilder(1024);
for (int i= 0;i<100;i++){
p.append(',');
p.append(i);
}
String s = p.toString();
System.out.println(s);
}
}
2、StringJoiner
// 用分割符拼接数组的需求
import java.util.StringJoiner;
public class Playing{
public static void main(String[] args) {
String[] names = {"Bob","Alice","Grace"};
var p = new StringJoiner(", ","Hello ", "!");
// StringJoiner("分隔符","前缀", "后缀")
for (String name : names) {
p.add(name);
}
System.out.println(p.toString());
}
}
// 实例
import java.util.StringJoiner;
public class Playing {
public static void main(String[] args) {
String[] fields = {"name", "position", "salary"};
String table = "employee";
String select = buildSelectSql(table, fields);
System.out.println(select);
System.out.println("SELECT name, position, salary FROM employee".equals(select) ? "测试成功" : "测试失败");
}
static String buildSelectSql(String table, String[] fields) {
var sql = new StringJoiner(", ", "SELECT ", " FROM " + table);
for (String field : fields) {
sql.add(field);
}
return sql.toString();
}
}
3、String.join()
/*String还提供了一个静态方法join(),这个方法在内部使用了StringJoiner来拼接字符串,在不需要指定“开头”和“结尾”的时候,用String.join()更方便*/
public class Playing{
public static void main(String[] args) {
String[] names = {"Bob","Alice","Grace"};
var s = String.join(", ",names);
System.out.println(s);
}
}