Here you can find the source of split(String str, String delim)
Parameter | Description |
---|---|
str | the String to tokenize |
delim | the delimiter String |
Parameter | Description |
---|---|
NullPointerException | if str or delim is null |
public static String[] split(String str, String delim)
//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; } }