/** * Splits a string into tokens, separated by the given delimiter. The * delimiter is not included in the resulting list, nor is it part of any of * the resulting tokens, except if there would be more tokens than maxTokens * would allow, in which case the last resulting token will contain some * delimiters. * <p> * If <code>wantEmptyTokens</code> is <code>true</code>, the last token * may also start with some of the delimiters which would otherwise mark * empty tokens. * * @param input * The string to split. * @param delimiter * The character used to separate tokens in the input string. * @param maxTokens * Maximum number of tokens to return. If there are less tokens * than this value, or as many as this value specifies, they are * all returned. If there would be more tokens, the last token * contains the rest of the string, including all delimiters * within it. <br> * If this value is zero or negative, then all instances of * the <code>delimiter</code> are considered to be split points. * @param wantEmptyTokens * <code>true</code> if consecutive delimiters must generate * empty tokens; <code>false</code> to output only tokens of * length 1 or more. * @return List of tokens found within the input string. */ public static List<String> split(final String input, final char delimiter, final int maxTokens, final boolean wantEmptyTokens) { if (maxTokens <= 0) return split(input, delimiter, wantEmptyTokens); final List<String> result = new ArrayList<String>(maxTokens); int curChar = 0; int nextChar = input.indexOf(delimiter, curChar); while (nextChar != -1) { if (input.charAt(curChar) != delimiter) { if (result.size() == maxTokens - 1) { result.add(input.substring(curChar)); return result; } result.add(input.substring(curChar, nextChar)); } else if (wantEmptyTokens) { if (result.size() == maxTokens - 1) { result.add(input.substring(curChar)); return result; } result.add(""); } curChar = nextChar; curChar++; nextChar = input.indexOf(delimiter, curChar); } if (curChar == input.length()) { // A delimiter ends the input. if (wantEmptyTokens) result.add(""); } else // Add the last token. result.add(input.substring(curChar)); return result; }