参见相关。net问题
我正在寻找一种快速简单的方法来做完全相反的分裂 这样["a","b","c"]就会变成"a,b,c"
遍历数组需要添加一个条件(如果这不是最后一个元素,则添加分隔符)或使用substring删除最后一个分隔符。
我相信有一种经过认证的、有效的方法来做到这一点(Apache Commons?)
你喜欢在你的项目中怎么做?
参见相关。net问题
我正在寻找一种快速简单的方法来做完全相反的分裂 这样["a","b","c"]就会变成"a,b,c"
遍历数组需要添加一个条件(如果这不是最后一个元素,则添加分隔符)或使用substring删除最后一个分隔符。
我相信有一种经过认证的、有效的方法来做到这一点(Apache Commons?)
你喜欢在你的项目中怎么做?
当前回答
如果你在Android上,你可以使用TextUtils。加入(分隔符,令牌)
其他回答
使用Java 8,你可以用一种非常干净的方式做到这一点:
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);
public String join(String[] str, String separator){
String retval = "";
for (String s: str){ retval+= separator + s;}
return retval.replaceFirst(separator, "");
}
它在StringUtils中:
http://www.java2s.com/Code/JavaAPI/org.apache.commons.lang/StringUtilsjoinObjectarrayStringseparator.htm
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();
}
“我相信有一种经过认证的、有效的方法来做到这一点(Apache Commons?)”
是的,很明显
StringUtils.join(array, separator)
http://www.java2s.com/Code/JavaAPI/org.apache.commons.lang/StringUtilsjoinObjectarrayStringseparator.htm