1、StringBuilder

  1. String s = "";
  2. for (int i=0;i<100;i++){
  3. s = s + "," + i;
  4. }
  5. /*每次拼接字符串都会丢掉旧的字符串,造成浪费内存;
  6. 为了高效拼接字符串,java标准库提供了StringBuilder,
  7. 它是一个可变对象,可以与存放缓冲区,增加字符时,不会创建新的临时对象
  8. */
  9. public class Playing{
  10. public static void main(String[] args) {
  11. StringBuilder p = new StringBuilder(1024);
  12. for (int i= 0;i<100;i++){
  13. p.append(',');
  14. p.append(i);
  15. }
  16. String s = p.toString();
  17. System.out.println(s);
  18. }
  19. }

2、StringJoiner

  1. // 用分割符拼接数组的需求
  2. import java.util.StringJoiner;
  3. public class Playing{
  4. public static void main(String[] args) {
  5. String[] names = {"Bob","Alice","Grace"};
  6. var p = new StringJoiner(", ","Hello ", "!");
  7. // StringJoiner("分隔符","前缀", "后缀")
  8. for (String name : names) {
  9. p.add(name);
  10. }
  11. System.out.println(p.toString());
  12. }
  13. }
  14. // 实例
  15. import java.util.StringJoiner;
  16. public class Playing {
  17. public static void main(String[] args) {
  18. String[] fields = {"name", "position", "salary"};
  19. String table = "employee";
  20. String select = buildSelectSql(table, fields);
  21. System.out.println(select);
  22. System.out.println("SELECT name, position, salary FROM employee".equals(select) ? "测试成功" : "测试失败");
  23. }
  24. static String buildSelectSql(String table, String[] fields) {
  25. var sql = new StringJoiner(", ", "SELECT ", " FROM " + table);
  26. for (String field : fields) {
  27. sql.add(field);
  28. }
  29. return sql.toString();
  30. }
  31. }

3、String.join()

  1. /*String还提供了一个静态方法join(),这个方法在内部使用了StringJoiner来拼接字符串,在不需要指定“开头”和“结尾”的时候,用String.join()更方便*/
  2. public class Playing{
  3. public static void main(String[] args) {
  4. String[] names = {"Bob","Alice","Grace"};
  5. var s = String.join(", ",names);
  6. System.out.println(s);
  7. }
  8. }