I want to join a String[]
with a glue string. Is there a function for this?
views:
2961answers:
6Apache Commons Lang has a StringUtils
class which has a join
function which will join arrays together to make a String
.
For example:
StringUtils.join(new String[] {"Hello", "World", "!"}, ", ")
Generates the following String
:
Hello, World, !
Not in core, no. A search for "java array join string glue" will give you some code snippets on how to achieve this though.
e.g.
public static String join(Collection s, String delimiter) {
StringBuffer buffer = new StringBuffer();
Iterator iter = s.iterator();
while (iter.hasNext()) {
buffer.append(iter.next());
if (iter.hasNext()) {
buffer.append(delimiter);
}
}
return buffer.toString();
}
Nothing built-in that I know of.
Apache Commons Lang has a class called StringUtils
which contains many join functions.
But then, you could easily write such a function with about ten lines of code. Like:
String combine(String[] s, String glue)
{
int k=s.length;
if (k==0)
return null;
StringBuilder out=new StringBuilder();
out.append(s[0]);
for (int x=1;x<k;++x)
out.append(glue).append(s[x]);
return out.toString();
}
Edit: A better signature might be combine(String glue, String... s), so you could pass it either an array or a comma-separated list of strings. Whatever.
java.util.Arrays has an 'asList' method. Together with the java.util.List/ArrayList API this gives you all you need:;
private static String[] join(String[] array1, String[] array2) {
List<String> list = new ArrayList<String>(Arrays.asList(array1));
list.addAll(Arrays.asList(array2));
return list.toArray(new String[0]);
}
I need to compose a variable length array of strings 10-2000. Is there a better method?