convert the array into string separated by default delimiter which is comma separator - Java Collection Framework

Java examples for Collection Framework:Array Join

Description

convert the array into string separated by default delimiter which is comma separator

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        char[] arr = new char[] { 'b', 'o', 'o', 'k', '2', 's', '.', 'c',
                'o', 'm', 'a', '1', };
        System.out.println(arrayAsString(arr));
    }/*from  w  w w  .  j  a v  a2  s  .c o m*/

    public static String arrayAsString(final char[] arr) throws Exception {

        return arrayAsString(arr, null);
    }

    public static String arrayAsString(final char[] arr,
            final String delimiter) throws Exception {

        final StringBuilder str = new StringBuilder();

        final int lastIndx = arr.length - 1;
        if (lastIndx == -1)
            return "[]";
        // str.append( "[" );

        for (int i = 0;; i++) {
            str.append(arr[i]);
            if (i == lastIndx)
                // return str.append( "]" ).toString();
                return str.toString();
            str.append(delimiter != null ? delimiter.toString() : ", ");
        }
    }

    /**
     * convert the array into string separated by default delimiter which is comma separator
     *
     * @param arr
     * @return
     * @throws Exception
     */
    public static String arrayAsString(final int[] arr) throws Exception {

        return arrayAsString(arr, null);
    }

    /**
     * convert the array into string separated by the delimiter
     *
     * @param arr
     * @param delimiter
     * @return
     * @throws Exception
     */
    public static String arrayAsString(final int[] arr,
            final String delimiter) throws Exception {

        final StringBuilder str = new StringBuilder();

        final int lastIndx = arr.length - 1;
        if (lastIndx == -1)
            return "[]";
        str.append("[");

        for (int i = 0;; i++) {
            str.append(arr[i]);
            if (i == lastIndx)
                return str.append("]").toString();
            str.append(delimiter != null ? delimiter.toString() : ", ");
        }
    }
}

Related Tutorials