A METHOD TO REVERSE EFFECT OF JAVA STRING.SPLIT()?

Pravesh Singh

Total Post:101

Points:709
Posted by  Pravesh Singh
Java 
 3860  View(s)
Ratings:
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,

  1. Ankita Pandey

    Post:183

    Points:1285
    Re: A method to reverse effect of java String.split()?

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

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!