Java Array Implode implode(String[] array, String separator)

Here you can find the source of implode(String[] array, String separator)

Description

Returns the given array joined by a separator.

License

Open Source License

Parameter

Parameter Description
array an array of strings to join
separator a string to insert between the array elements

Return

the full string result

Declaration

public static String implode(String[] array, String separator) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.List;

public class Main {
    /**//from  w w w.  j a  v  a 2s  .c  o  m
     * Returns the given array joined by a separator.
     *
     * @param array     an array of strings to join
     * @param separator a string to insert between the array elements
     * @return the full string result
     */
    public static String implode(String[] array, String separator) {
        if (array.length == 0) {
            return "";
        }

        StringBuilder buffer = new StringBuilder();

        for (String str : array) {
            buffer.append(separator);
            buffer.append(str);
        }

        return buffer.substring(separator.length()).trim();
    }

    /**
     * Returns the elements joined by a separator.
     *
     * @param list      a List object to join together
     * @param separator a string to insert between the list elements
     * @return the full string result
     */
    public static String implode(List<?> list, String separator) {
        if (list.isEmpty()) {
            return "";
        }

        StringBuilder buffer = new StringBuilder();

        int lastElement = list.size() - 1;
        for (int i = 0; i < list.size(); i++) {
            buffer.append(list.get(i).toString());

            if (i < lastElement) {
                buffer.append(separator);
            }
        }

        return buffer.toString();
    }
}

Related

  1. implode(final String[] pStrArray)
  2. implode(Object[] array, String separator)
  3. implode(Object[] ary, String delim)
  4. implode(String delim, Object[] objects)
  5. implode(String delim, String[] args)
  6. implode(String[] data, String glue)
  7. implode(String[] inputArray, String glueString)
  8. implode(String[] values, String separator, String beforeEach, String afterEach)
  9. implodeArray(Object[] array)