在 Java 中使用分隔符(与拆分相反)连接数组元素的快速简便方法 [英] A quick and easy way to join array elements with a separator (the opposite of split) in Java
问题描述
参见相关.NET问题
我正在寻找一种与拆分完全相反的快速简便的方法这样它就会导致 ["a","b","c"]
变成 "a,b,c"
I'm looking for a quick and easy way to do exactly the opposite of split
so that it will cause ["a","b","c"]
to become "a,b,c"
遍历数组需要添加条件(如果这不是最后一个元素,则添加分隔符)或使用子字符串删除最后一个分隔符.
Iterating through an array requires either adding a condition (if this is not the last element, add the seperator) or using substring to remove the last separator.
我确定有一种经过认证的有效方法(Apache Commons?)
I'm sure there is a certified, efficient way to do it (Apache Commons?)
你更喜欢在你的项目中如何做?
How do you prefer doing it in your projects?
推荐答案
使用 Java 8,您可以以一种非常干净的方式做到这一点:
Using Java 8 you can do this in a very clean way:
String.join(delimiter, elements);
这以三种方式起作用:
1) 直接指定元素
String joined1 = String.join(",", "a", "b", "c");
2) 使用数组
String[] array = new String[] { "a", "b", "c" };
String joined2 = String.join(",", array);
3) 使用可迭代对象
List<String> list = Arrays.asList(array);
String joined3 = String.join(",", list);
这篇关于在 Java 中使用分隔符(与拆分相反)连接数组元素的快速简便方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!