参见相关。net问题
我正在寻找一种快速简单的方法来做完全相反的分裂 这样["a","b","c"]就会变成"a,b,c"
遍历数组需要添加一个条件(如果这不是最后一个元素,则添加分隔符)或使用substring删除最后一个分隔符。
我相信有一种经过认证的、有效的方法来做到这一点(Apache Commons?)
你喜欢在你的项目中怎么做?
参见相关。net问题
我正在寻找一种快速简单的方法来做完全相反的分裂 这样["a","b","c"]就会变成"a,b,c"
遍历数组需要添加一个条件(如果这不是最后一个元素,则添加分隔符)或使用substring删除最后一个分隔符。
我相信有一种经过认证的、有效的方法来做到这一点(Apache Commons?)
你喜欢在你的项目中怎么做?
当前回答
The approach that I've taken has evolved since Java 1.0 to provide readability and maintain reasonable options for backward-compatibility with older Java versions, while also providing method signatures that are drop-in replacements for those from apache commons-lang. For performance reasons, I can see some possible objections to the use of Arrays.asList but I prefer helper methods that have sensible defaults without duplicating the one method that performs the actual work. This approach provides appropriate entry points to a reliable method that does not require array/list conversions prior to calling.
Java版本兼容性的可能变化包括用StringBuffer (Java 1.0)代替StringBuilder (Java 1.5),切换出Java 1.5迭代器,并从集合(Java 1.2)中删除通用通配符(Java 1.5)。如果想进一步提高向后兼容性,可以删除使用Collection的方法,并将逻辑移到基于数组的方法中。
public static String join(String[] values)
{
return join(values, ',');
}
public static String join(String[] values, char delimiter)
{
return join(Arrays.asList(values), String.valueOf(delimiter));
}
// To match Apache commons-lang: StringUtils.join(values, delimiter)
public static String join(String[] values, String delimiter)
{
return join(Arrays.asList(values), delimiter);
}
public static String join(Collection<?> values)
{
return join(values, ',');
}
public static String join(Collection<?> values, char delimiter)
{
return join(values, String.valueOf(delimiter));
}
public static String join(Collection<?> values, String delimiter)
{
if (values == null)
{
return new String();
}
StringBuffer strbuf = new StringBuffer();
boolean first = true;
for (Object value : values)
{
if (!first) { strbuf.append(delimiter); } else { first = false; }
strbuf.append(value.toString());
}
return strbuf.toString();
}
其他回答
所有这些其他答案都包括运行时开销……比如使用ArrayList.toString(). replaceall(…),这是非常浪费的。
我会给出零开销的最优算法; 它看起来不像其他选项那么漂亮,但在内部,这是它们都在做的事情(在成堆的其他隐藏检查、多个数组分配和其他杂事之后)。
因为您已经知道您正在处理字符串,所以您可以通过手动执行所有操作来节省大量的数组分配。这并不漂亮,但如果跟踪其他实现所执行的实际方法调用,您将看到它的运行时开销可能最少。
public static String join(String separator, String ... values) {
if (values.length==0)return "";//need at least one element
//all string operations use a new array, so minimize all calls possible
char[] sep = separator.toCharArray();
// determine final size and normalize nulls
int totalSize = (values.length - 1) * sep.length;// separator size
for (int i = 0; i < values.length; i++) {
if (values[i] == null)
values[i] = "";
else
totalSize += values[i].length();
}
//exact size; no bounds checks or resizes
char[] joined = new char[totalSize];
int pos = 0;
//note, we are iterating all the elements except the last one
for (int i = 0, end = values.length-1; i < end; i++) {
System.arraycopy(values[i].toCharArray(), 0,
joined, pos, values[i].length());
pos += values[i].length();
System.arraycopy(sep, 0, joined, pos, sep.length);
pos += sep.length;
}
//now, add the last element;
//this is why we checked values.length == 0 off the hop
System.arraycopy(values[values.length-1].toCharArray(), 0,
joined, pos, values[values.length-1].length());
return new String(joined);
}
你可以用正则表达式来使用replace和replaceAll。
String[] strings = {"a", "b", "c"};
String result = Arrays.asList(strings).toString().replaceAll("(^\\[|\\]$)", "").replace(", ", ",");
因为Arrays.asList(). tostring()生成:"[a, b, c]",我们执行replaceAll来删除第一个和最后一个括号,然后(可选地)您可以更改","序列为","(您的新分隔符)。
精简版(字符数更少):
String[] strings = {"a", "b", "c"};
String result = ("" + Arrays.asList(strings)).replaceAll("(^.|.$)", "").replace(", ", "," );
正则表达式非常强大,特别是字符串方法“replaceFirst”和“replaceAll”。试一试吧。
更简单的是,你可以使用数组,所以你会得到一个字符串,数组的值由","隔开
String concat = Arrays.toString(myArray);
所以你会得到这样的结果:concat = "[a,b,c]"
更新
然后,您可以使用Jeff建议的子字符串来消除括号
concat = concat.substring(1, concat.length() -1);
所以你得到concat = "a,b,c"
如果你想使用Kotlin:
val concat = myArray.joinToString(separator = ",") //"a,b,c"
如果你在Android上,你可以使用TextUtils。加入(分隔符,令牌)
这个选项是快速和清晰的:
public static String join(String separator, String... values) {
StringBuilder sb = new StringBuilder(128);
int end = 0;
for (String s : values) {
if (s != null) {
sb.append(s);
end = sb.length();
sb.append(separator);
}
}
return sb.substring(0, end);
}