• java8 字符串拼接 StringJoiner


    今天在公众号中看见对字符串拼接,之前项目中都是用的StringBuilder,今天无意间发现StringJoiner,上代码测试下!

    StringBuilder拼接字符串,以逗号分隔

    StringBuilder拼接字符串,以逗号分隔
    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append("小");
    stringBuilder.append(",");
    stringBuilder.append("康");
    System.out.println(stringBuilder.toString());

    输出: 小,康

    StringJoiner拼接字符串,以逗号分隔
    StringJoiner stringJoiner = new StringJoiner(",");
    stringJoiner.add("小").add("康");
    System.out.println(stringJoiner.toString());

    输出: 小,康
    StringBuilder拼接字符串,以逗号分隔,以中括号作为前后缀
    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append("[");
    stringBuilder.append("小");
    stringBuilder.append(",");
    stringBuilder.append("康");
    stringBuilder.append("]");
    System.out.println(stringBuilder.toString());
    输出: [小,康]
    StringJoiner拼接字符串,以逗号分隔,以中括号作为前后缀
    StringJoiner stringJoiner = new StringJoiner(",","[","]");
    stringJoiner.add("小").add("康");
    System.out.println(stringJoiner.toString());
    输出: [小,康]

    其实StringJoiner底层也是用StringBuilder进行字符串拼接,只是帮我们进行了封装,不过在实际中,针对不同的场景使用不同方法,就看各位的了!!

    补充:简单的字符串拼接String.join,查看join方法,也是用StringJoiner进行拼接的
    // 简单的字符串拼接
    String c = String.join(",","小","康");
    System.out.println(c);
    输出:小,康
    
    
  • 相关阅读:
    2018.09.25python学习第十天part3
    2018.09.25python学习第十天part2
    2018.09.25python学习第十天part1
    2018.09.21python学习第九天part3
    2018.09.21python学习第九天part2
    2018.09.21python学习第九天part1
    2018.09.20python作业
    Alpha 冲刺(3/10)
    Alpha 冲刺(2/10)
    Alpha 冲刺(1/10)
  • 原文地址:https://www.cnblogs.com/xiaokangk/p/14079545.html
Copyright © 2020-2023  润新知