Java array join String[] array to String

Description

Java array join String[] array to String


//package com.demo2s;

import java.util.Collection;

public class Main {
    public static void main(String[] argv) throws Exception {
        Object[] tokens = new String[] { "CSS", "HTML", "Java", null, "demo2s.com", "Javascript 123" };
        String delimiter = "";
        System.out.println(join(tokens, delimiter));
    }/*from  w  ww . j av  a2  s .c o  m*/

    /**
     * Concatenates the String representations of the elements of a
     * String[] array into one String, and inserts a delimiter between
     * each pair of elements.
     * <p>
     * This includes the String[] case, because if s is a String, then
     * s.toString() returns s.
     *
     */
    public static String join(Object[] tokens, String delimiter) {
        if (tokens == null || tokens.length == 0)
            return "";
        StringBuilder result = new StringBuilder();

        for (int i = 0; i < tokens.length; i++) {
            if (i > 0 && delimiter != null)
                result.append(delimiter);

            if (tokens[i] != null)
                result.append(tokens[i].toString());
        }
        return result.toString();
    }
}



PreviousNext

Related