Java String Split by Delimiter splitStr(String str, char delimiter, boolean trim)

Here you can find the source of splitStr(String str, char delimiter, boolean trim)

Description

Splits string by delimiter.

License

Open Source License

Parameter

Parameter Description
str a parameter
delimiter a parameter

Declaration

public static List<String> splitStr(String str, char delimiter, boolean trim) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2012 eBay Inc. and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:/* w ww.j  a  va2s.c o m*/
 *     eBay Inc. - initial API and implementation
 *******************************************************************************/

import java.util.ArrayList;

import java.util.List;

public class Main {
    public static List<String> splitStr(String str, char delimiter) {
        return splitStr(str, delimiter, false);
    }

    /**
     * Splits string by delimiter. If delimiter is the last character
     * of the string, empty substring after that will not be added
     * to the result.
     * 
     * @param str
     * @param delimiter
     * @return
     */
    public static List<String> splitStr(String str, char delimiter, boolean trim) {
        int startPos = 0;
        final List<String> result = new ArrayList<String>();
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (c == delimiter) {
                String subStr = str.substring(startPos, i);
                if (trim) {
                    subStr = subStr.trim();
                }
                result.add(subStr);
                startPos = i + 1;
                continue;
            }
        }
        if (startPos < str.length()) {
            String subStr = str.substring(startPos, str.length());
            if (trim) {
                subStr = subStr.trim();
            }
            result.add(subStr);
        }
        return result;
    }
}

Related

  1. splitNoCoalesce(String s, char delimiter)
  2. splitOnEntireString(String target, String delimiter)
  3. splitSimple(String delimiter, String str)
  4. splitSimpleLimit(String str, String delimiter, int limitSize)
  5. splitSqlScript(String script, char delim, List statements)
  6. splitString(CharSequence s, char delim)
  7. splitString(final String values, final char delimiter)
  8. splitString(String data, String delimiter)
  9. splitString(String originalString, String delimeter)