有这个:
List<String> elementNames = Arrays.asList("h1", "h2", "h3", "h4", "h5", "h6");
使用自定义分隔符获取String的优雅方法是什么,如下所示:
"h1,h2,h3,h4,h5,h6"
答案 0 :(得分:37)
StringBuilder sb = new StringBuilder();
for(String s: elementnames) {
sb.append(s).append(',');
}
sb.deleteCharAt(sb.length()-1); //delete last comma
String newString = sb.toString();
更新:启动java 8,您可以使用以下方法获得相同的结果:
List<String> elementNames = Arrays.asList("1", "2", "3");
StringJoiner joiner = new StringJoiner(",", "", "");
elementNames.forEach(joiner::add);
System.out.println(joiner.toString());
答案 1 :(得分:27)
如果您不介意使用apache提供的StringUtils库,您可以这样做:
// Output is "a,b,c"
StringUtils.join(["a", "b", "c"], ',');