This question already has an answer here:
- Java: function for arrays like PHP's join()? 22 answers
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.
I'm sure there is a certified, efficient way to do it (Apache Commons?)
How do you prefer doing it in your projects?
A fast and simple solution without any 3rd party includes.
If you're on Android you can
TextUtils.join(delimiter, tokens)
You can use replace and replaceAll with regular expressions.
Because
Arrays.asList().toString()
produces: "[a, b, c]", we do areplaceAll
to remove the first and last brackets and then (optionally) you can change the ", " sequence for "," (your new separator).A stripped version (fewer chars):
Regular expressions are very powerful, specially String methods "replaceFirst" and "replaceAll". Give them a try.
This small function always comes in handy.
Apache Commons Lang does indeed have a
StringUtils.join
method which will connectString
arrays together with a specified separator.For example:
However, I suspect that, as you mention, there must be some kind of conditional or substring processing in the actual implementation of the above mentioned method.
If I were to perform the
String
joining and didn't have any other reasons to use Commons Lang, I would probably roll my own to reduce the number of dependencies to external libraries."I'm sure there is a certified, efficient way to do it (Apache Commons?)"
yes, apparenty it's
http://www.java2s.com/Code/JavaAPI/org.apache.commons.lang/StringUtilsjoinObjectarrayStringseparator.htm