I am looking for a method to combine an array of strings into a delimited String. An opposite to split(). I've seen this in other languages.
Wanted to ask the forum before I try writing my own( since the JDK has everything...)
Thanks,
I am looking for a method to combine an array of strings into a delimited String. An opposite to split(). I've seen this in other languages.
Wanted to ask the forum before I try writing my own( since the JDK has everything...)
Thanks,
There's no method in the JDK for this that I'm aware of. Apache Commons Lang has various overloaded join methods that do what you want.
There are several examples on DZone Snippets if you want to roll your own that works with a Collection. For example:
public static String join(AbstractCollection<String> s, String delimiter) {
if (s == null || s.isEmpty()) return "";
Iterator<String> iter = s.iterator();
StringBuilder builder = new StringBuilder(iter.next());
while( iter.hasNext() )
{
builder.append(delimiter).append(iter.next());
}
return builder.toString();
}
I got the following example here
/*
7) Join Strings using separator >>>AB$#$CD$#$EF
*/
import org.apache.commons.lang.StringUtils;
public class StringUtilsTrial {
public static void main(String[] args) {
// Join all Strings in the Array into a Single String, separated by $#$
System.out.println("7) Join Strings using separator >>>"
+ StringUtils.join(new String[] { "AB", "CD", "EF" }, "$#$"));
}
}
Google also provides a joiner class in their Google Collections library:
Based on all the previous answers:
public static String join(Iterable<? extends Object> elements, CharSequence separator)
{
StringBuilder builder = new StringBuilder();
if (elements != null)
{
Iterator<? extends Object> iter = elements.iterator();
if(iter.hasNext())
{
builder.append( String.valueOf( iter.next() ) );
while(iter.hasNext())
{
builder
.append( separator )
.append( String.valueOf( iter.next() ) );
}
}
}
return builder.toString();
}