Java String Split by Delimiter splitToArray(String stringToSplit, String delimitter, boolean trim)

Here you can find the source of splitToArray(String stringToSplit, String delimitter, boolean trim)

Description

split To Array

License

Open Source License

Declaration

public static final String[] splitToArray(String stringToSplit,
            String delimitter, boolean trim) 

Method Source Code

//package com.java2s;
/**/*from   w w  w  .j a  v  a 2  s  .  c om*/
 * Copyright (c) 2014 Xiufeng Liu ( xiufeng.liu@uwaterloo.ca )
 * <p/>
 * This file is free software: you may copy, redistribute and/or modify it
 * under the terms of the GNU General Public License version 2
 * as published by the Free Software Foundation.
 * <p/>
 * This file 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.
 * <p/>
 * 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 {
    public static final String[] splitToArray(String stringToSplit,
            String delimitter, boolean trim) {
        if (stringToSplit == null) {
            return new String[] {};
        }
        if (delimitter == null) {
            throw new IllegalArgumentException();
        }
        StringTokenizer tokenizer = new StringTokenizer(stringToSplit,
                delimitter, false);
        int count = tokenizer.countTokens();
        String[] splitTokens = new String[count];
        for (int i = 0; i < count; ++i) {
            String token = tokenizer.nextToken();
            if (trim) {
                token = token.trim();
            }
            splitTokens[i] = token;
        }
        return splitTokens;
    }

    public static String trim(String str, char ch) {
        if (null == str)
            return null;
        str = str.trim();
        int count = str.length();
        int len = str.length();
        int st = 0;

        char[] val = str.toCharArray();

        while ((st < len) && (val[st] == ch)) {
            st++;
        }
        while ((st < len) && (val[len - 1] == ch)) {
            len--;
        }
        return ((st > 0) || (len < count)) ? str.substring(st, len) : str;
    }
}

Related

  1. splitString(String str, String delims)
  2. splitString(String toSplit, String delimiter)
  3. splitStringList(String strList, String delimit)
  4. splitStringUsingDelimiter(String name, String delimiter)
  5. splitText(String text, String delimiter)
  6. splitToken(String str, String delimiter)
  7. splitToList(final String string, final String delim, final int limit)
  8. splitToList(String a_text, String a_delimiter)
  9. splitToList(String s, String delimRegEx)