Java String Split by Delimiter split(String str, String delim)

Here you can find the source of split(String str, String delim)

Description

Returns a list of substrings created by splitting the given string at the given delimiter.

License

Apache License

Parameter

Parameter Description
str the string we're splitting
delim the delimter string

Declaration

public static List<String> split(String str, String delim) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.util.*;

public class Main {
    /**/*from w w w . ja  va 2  s.  co  m*/
     * Returns a list of substrings created by splitting the given string at
     * the given delimiter. The return value will be <code>null</code> if the
     * string is <code>null</code>, else it will be a non-empty list of strings.
     * If <var>delim</var> is <code>null</code> or is not found in the string,
     * the list will contain one element: the original string.
     * <p>
     * This isn't the same thing as using a tokenizer. <var>delim</var> is
     * a literal string, not a set of characters any of which may be a
     * delimiter.
     *
     * @param str the string we're splitting
     * @param delim the delimter string
     */
    public static List<String> split(String str, String delim) {
        if (str == null)
            return null;

        ArrayList<String> list = new ArrayList<String>();

        if (delim == null) {
            list.add(str);
            return list;
        }

        int subStart, afterDelim = 0;
        int delimLength = delim.length();
        while ((subStart = str.indexOf(delim, afterDelim)) != -1) {
            list.add(str.substring(afterDelim, subStart));
            afterDelim = subStart + delimLength;
        }
        if (afterDelim <= str.length())
            list.add(str.substring(afterDelim));

        return list;
    }
}

Related

  1. split(String str, char delimiter, boolean trim)
  2. split(String str, int delim, String trailing)
  3. split(String str, String delim)
  4. split(String str, String delim)
  5. split(String str, String delim)
  6. split(String str, String delim)
  7. split(String str, String delim)
  8. split(String str, String delimeter)
  9. split(String str, String delimiter)