Joins a string array based on the delimiter - Java Collection Framework

Java examples for Collection Framework:Array Element

Description

Joins a string array based on the delimiter

Demo Code


//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String[] strings = new String[] { "1", "abc", "level", null,
                "book2s.com", "asdf 123" };
        System.out.println(join(strings));
    }/*from ww w .j a v  a  2  s .  co m*/

    /**
     * Joins a string array based on the delimiter
     * 
     * @param strings
     * @return
     */
    public static String join(String[] strings) {
        return join(strings, ",");
    }

    public static String join(String[] strings, String delim) {
        return join(strings, ",", false);
    }

    public static String join(String[] strings, String delim,
            boolean toUpper) {
        StringBuilder sb = new StringBuilder();
        boolean start = true;
        for (String string : strings) {
            if (start) {
                start = false;
            } else {
                sb.append(delim);
            }
            String appendString = toUpper ? string.toUpperCase() : string;
            sb.append(appendString);
        }
        return sb.toString();
    }
}

Related Tutorials