Java String Split by Delimiter split(final String input, final String delimiter, final boolean removeEmpty)

Here you can find the source of split(final String input, final String delimiter, final boolean removeEmpty)

Description

Implementation of a non regex-based string splitting utility.

License

Apache License

Parameter

Parameter Description
input The input string to split.
delimiter The splitting delimiter.
removeEmpty Whether to remove empty substrings from the result.

Return

An array of substrings separated by the given delimiter.

Declaration

public static String[] split(final String input, final String delimiter, final boolean removeEmpty) 

Method Source Code


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

import java.util.ArrayList;

public class Main {
    /**/*from   www .ja v a  2  s  .c  o m*/
     * Implementation of a non regex-based string splitting utility. Returns an
     * array of each substring within {@code input} that is delimited
     * (separated) by the string {@code delimiter}, optionally removing empty
     * substrings. For example,
     * 
     * <pre>
     * <code>
     * split("1,2,,3,4,5,", ",", true) = ["1", "2", "3", "4", "5"]
     * split("1,2,,3,4,5,", ",", false) = ["1", "2", "", "3", "4", "5", ""]
     * </code>
     * </pre>
     * 
     * This non regex-based implementation is used for speed.
     *
     * @param input
     *            The input string to split.
     * @param delimiter
     *            The splitting delimiter.
     * @param removeEmpty
     *            Whether to remove empty substrings from the result.
     * @return An array of substrings separated by the given delimiter.
     */
    public static String[] split(final String input, final String delimiter, final boolean removeEmpty) {
        if (input.length() > 0) {
            final ArrayList<String> parts = new ArrayList<String>();
            int beginIndex = 0, endIndex;
            while ((endIndex = input.indexOf(delimiter, beginIndex)) != -1) {
                parts.add(input.substring(beginIndex, endIndex));
                beginIndex = endIndex + delimiter.length();
            }

            parts.add(input.substring(beginIndex));

            final String[] partsArray = new String[parts.size()];
            for (int i = 0; i < partsArray.length; i++) {
                partsArray[i] = parts.get(i);
            }
            return parts.toArray(partsArray);
        } else {
            return new String[0];
        }
    }
}

Related

  1. fastSplit(String string, char delimiter)
  2. fastSplit(String string, String delimiter)
  3. split(final boolean enable, final String value, final char delimiter)
  4. split(final String input, final char delimiter)
  5. split(final String src, final char delim)
  6. split(final String str, final char delim)
  7. split(final String str, final String delimiter)
  8. split(String a, String delim)