StringJoiner字符串分隔拼接

125 阅读1分钟

用StringJoiner 做字符串拼接

  • API 包括 setEmptyValue:设置空值 toString:转换成 String add:添加字符串 merge:从另一个 StringJoiner 合并 length:长度(包括前缀后缀)
StringJoiner stringJoiner = new StringJoiner(",").add("hello").add("world").add("moximoxi");

输出结果:hello,world,moximoxi

StringJoiner stringJoiner = new StringJoiner(",", "[", "]");
 stringJoiner.add("hello");
 stringJoiner.add("world");
 stringJoiner.add("moximoxi");

输出结果:[hello,world,moximoxi]

  • JDK1.8 String也封装了stringJoiner 让拼接操作变得更简单
String str = String.join(",", "hello", "world", "moximoxi");