Java String Split by Delimiter split(String string, String delim, boolean doTrim)

Here you can find the source of split(String string, String delim, boolean doTrim)

Description

Splits a string into tokens.

License

Apache License

Parameter

Parameter Description
string the String
delim the delimiter
doTrim should each token be trimmed

Return

the array of tokens

Declaration

public static String[] split(String string, String delim, boolean doTrim) 

Method Source Code

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

import java.util.ArrayList;

import java.util.List;

public class Main {
    /**//from  ww w  .java  2s . c o  m
     * Splits a string into tokens. Similar to <code>StringTokenizer</code>
     * except that empty tokens are recognized and added as <code>null</code>.
     * With a delimiter of <i>";"</i> the string
     * <i>"a;;b;c;;"</i> will split into
     * <i>["a"] [null] ["b"] ["c"] [null]</i>.
     * @param string the String
     * @param delim the delimiter
     * @param doTrim should each token be trimmed
     * @return the array of tokens
     */
    public static String[] split(String string, String delim, boolean doTrim) {
        int pos = 0, begin = 0;
        List<String> resultList = new ArrayList<>();
        while ((-1 != (pos = string.indexOf(delim, begin))) && (begin < string.length())) {
            String token = string.substring(begin, pos);
            if (doTrim)
                token = token.trim();
            if (token.length() == 0)
                token = null;
            resultList.add(token);
            begin = pos + delim.length();
        }
        if (begin < string.length()) {
            String token = string.substring(begin);
            if (doTrim)
                token = token.trim();
            if (token.length() == 0)
                token = null;
            resultList.add(token);
        }
        return resultList.toArray(new String[resultList.size()]);
    }
}

Related

  1. split(String str, String delimiter)
  2. split(String str, String delimiter)
  3. split(String str, String delimiter, int limit)
  4. split(String str, String delims)
  5. split(String str, String regexDelim, int limitUseRegex)
  6. split(String string, String delimiter)
  7. split(String string, String delimiter)
  8. split(String stringToSplit, char delimiter)
  9. split(String strToSplit, char delimiter)