Home > DeveloperSection > Forums > A method to reverse effect of java String.split()?
Pravesh Singh
Pravesh Singh

Total Post:101

Points:709
Posted on    September-28-2013 6:27 AM

 Java Java 
Ratings:


 1 Reply(s)
 2721  View(s)
Rate this:
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,



Ankita Pandey
Ankita Pandey

Total Post:183

Points:1285
Posted on    September-28-2013 6:55 AM

Hey Pravesh!

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();
}

Don't want to miss updates? Please click the below button!

Follow MindStick