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 tokens delimited by delim in String str.

License

GNU General Public License

Parameter

Parameter Description
str the String to tokenize
delim the delimiter String

Exception

Parameter Description
NullPointerException if str or delim is null

Return

the String tokens

Declaration

public static String[] split(String str, String delim) 

Method Source Code


//package com.java2s;
/*//from   w ww. java  2  s  .co m
 * Copyright (C) 2002-2017 FlyMine
 *
 * This code may be freely distributed and modified under the
 * terms of the GNU Lesser General Public Licence.  This should
 * be distributed with the code.  See the LICENSE file for more
 * information or http://www.gnu.org/copyleft/lesser.html.
 *
 */

import java.util.ArrayList;

import java.util.List;

public class Main {
    /**
     * Returns a list of tokens delimited by delim in String str.
     * eg. split("abc@#def@#", "@#") returns a 3 element array containing "abc", "def" and ""
     *
     * @param str the String to tokenize
     * @param delim the delimiter String
     * @return the String tokens
     * @throws NullPointerException if str or delim is null
     */
    public static String[] split(String str, String delim) {
        if (str == null || delim == null) {
            throw new NullPointerException("Cannot pass null arguments to tokenize");
        }

        if (delim.length() == 0) {
            throw new IllegalArgumentException("Delimiter can not be zero length");
        }

        List<Integer> l = new ArrayList<Integer>();

        int nextStartIndex = 0;

        while (true) {
            int delimIndex = str.indexOf(delim, nextStartIndex);
            if (delimIndex == -1) {
                break;
            }
            l.add(new Integer(delimIndex));
            nextStartIndex = delimIndex + delim.length();
        }

        // add list sentinel to avoid the special case for the last token
        l.add(new Integer(str.length()));

        String[] returnArray = new String[l.size()];

        int i = 0;
        int lastDelimStart = -delim.length();
        for (Integer thisDelimStartInteger : l) {
            int thisDelimStart = thisDelimStartInteger.intValue();
            returnArray[i] = str.substring(lastDelimStart + delim.length(), thisDelimStart);
            lastDelimStart = thisDelimStart;
            i++;
        }

        return returnArray;
    }
}

Related

  1. split(String str, char delimiter)
  2. split(String str, char delimiter, boolean trim)
  3. split(String str, int delim, String trailing)
  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 delim)
  9. split(String str, String delimeter)