Duplicates PHP's "implode" functionality. - Java java.lang

Java examples for java.lang:String Join

Description

Duplicates PHP's "implode" functionality.

Demo Code

//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String[] ary = new String[] { "1", "abc", "level", null,
                "java2s.com", "asdf 123" };
        String delim = "java2s.com";
        System.out.println(implode(ary, delim));
    }/*from  w w w  .  ja  v  a2 s. c o m*/

    /**
     * Duplicates PHP's "implode" functionality. Will glue an array of
     * strings together with the delimiter: <br />
     * foo[0] = "Dave,";<br />
     * foo[1] = "hello";<br />
     * foo[2] = "world";<br />
     * implode(foo, " ") => "Dave, hello world"
     *
     * @param ary the array of strings to glue
     * @param delim the glue
     * @return the imploded string
     */
    public static String implode(String[] ary, String delim) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < ary.length; i++) {
            if (i != 0) {
                sb.append(delim);
            }
            sb.append(ary[i]);
        }
        return sb.toString();
    }
}

Related Tutorials