Java Array Join join(String[] names, String sep)

Here you can find the source of join(String[] names, String sep)

Description

Concatenate the strings in @p names, placing @p sep between each (except at the end) and return the resulting string.

License

Open Source License

Declaration

public static String join(String[] names, String sep) 

Method Source Code


//package com.java2s;
import java.util.List;

public class Main {
    /**//from  w ww.  j a va 2  s .  c  om
    * Concatenate the strings in @p names, placing @p sep
    * between each (except at the end) and return the resulting
    * string.
    *
    * @see QStringList::join
    *
    * Test cases:
    *   - null separator, empty separator, one-character and longer string separator
    *   - null names, 0-length names, 1 name, n names
    */
    public static String join(String[] names, String sep) {
        if (names == null) {
            return null;
        }
        int l = names.length;

        if (l < 1) {
            return "";
        }

        // This is just a (bad) guess at the capacity required
        StringBuilder b = new StringBuilder(l * sep.length() + l + 1);
        for (int i = 0; i < l; i++) {
            b.append(names[i]);
            if ((i < (l - 1)) && (sep != null)) {
                b.append(sep);
            }
        }
        return b.toString();
    }

    /**
     * Overload of join() for use with List.
     *
     * @param names List of strings to join together
     * @param sep   Separator between strings (may be null)
     * @return null if names is null; strings in names joined with
     *          sep in between otherwise.
     */
    public static String join(List<String> names, String sep) {
        if (names == null) {
            return null;
        }
        int l = names.size();
        if (l < 1) {
            return "";
        }

        // This is just a (bad) guess at the capacity required
        StringBuilder b = new StringBuilder(l * sep.length() + l + 1);
        int i = 0;
        for (String s : names) {
            b.append(s);
            if ((i < (l - 1)) && (sep != null)) {
                b.append(sep);
            }
        }
        return b.toString();
    }
}

Related

  1. join(String[] inputArray, String glueString)
  2. join(String[] items, String delimiter)
  3. join(String[] lines, String delim)
  4. join(String[] lines, String sep)
  5. join(String[] lines, String separator)
  6. join(String[] parts, String separator)
  7. join(String[] sentence, String separator)
  8. join(String[] strArr)
  9. join(String[] strArray, String delimiter)