Here you can find the source of splitNoCoalesce(String s, char delimiter)
public static String[] splitNoCoalesce(String s, char delimiter)
//package com.java2s; /*//from w w w .j a v a 2 s. c om * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import java.util.*; public class Main { /** * Exactly like splitNoCoalesce(s, Character.toString(delimiter)) */ public static String[] splitNoCoalesce(String s, char delimiter) { return splitNoCoalesce(s, Character.toString(delimiter)); } /** * Similar to split(s, delimiters) except that subsequent delimiters are not * coalesced, so the returned array may contain empty strings. If s starts * (ends) with a delimiter, the returned array starts (ends) with an empty * strings. If s contains N delimiters, N+1 strings are always returned. * Examples: * * <pre> * split("a//b/ c /","/")=={"a","","b"," c ", ""} * split("a b", "/")=={"a b"}. * split("///", "/")=={"","","",""}. * </pre> * * @return an array A s.t. s.equals(A[0]+d0+A[1]+d1+...+A[N]), where * for all dI, dI.size()==1 && delimiters.indexOf(dI)>=0; and for * all c in A[i], delimiters.indexOf(c)<0 */ public static String[] splitNoCoalesce(String s, String delimiters) { //Tokenize s based on delimiters, adding to buffer. StringTokenizer tokenizer = new StringTokenizer(s, delimiters, true); List<String> tokens = new ArrayList<String>(); //True if last token was a delimiter. Initialized to true to force //an empty string if s starts with a delimiter. boolean gotDelimiter = true; while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); //Is token a delimiter? if (token.length() == 1 && delimiters.indexOf(token) >= 0) { //If so, add blank only if last token was a delimiter. if (gotDelimiter) tokens.add(""); gotDelimiter = true; } else { //If not, add "real" token. tokens.add(token); gotDelimiter = false; } } //Add trailing empty string UNLESS s is the empty string. if (gotDelimiter && !tokens.isEmpty()) tokens.add(""); return tokens.toArray(new String[0]); } }