今天在公众号中看见对字符串拼接,之前项目中都是用的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);
输出:小,康