Java String Split by Delimiter splitString(String str, String delimiter)

Here you can find the source of splitString(String str, String delimiter)

Description

Manual split function to avoid depending on guava.

License

Apache License

Parameter

Parameter Description
str the string to be split
delimiter the delimiter

Return

split string array

Declaration

public static String[] splitString(String str, String delimiter) 

Method Source Code

//package com.java2s;
/*//from   w  ww  .j av  a 2s  .  co m
 * Copyright [2012-2014] PayPal Software Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.util.*;

public class Main {
    /**
     * Manual split function to avoid depending on guava.
     *
     * <p>
     * Some examples: "^"=&gt;[, ]; ""=&gt;[]; "a"=&gt;[a]; "abc"=&gt;[abc]; "a^"=&gt;[a, ]; "^b"=&gt;[, b];
     * "^^b"=&gt;[, , b]
     *
     * @param str
     *            the string to be split
     * @param delimiter
     *            the delimiter
     * @return split string array
     */
    public static String[] splitString(String str, String delimiter) {
        if (str == null || str.length() == 0) {
            return new String[] { "" };
        }

        List<String> categories = new ArrayList<String>();
        int dLen = delimiter.length();
        int begin = 0;
        for (int i = 0; i < str.length(); i++) {
            if (str.substring(i, Math.min(i + dLen, str.length())).equals(delimiter)) {
                categories.add(str.substring(begin, i));
                begin = i + dLen;
            }
            if (i == str.length() - 1) {
                categories.add(str.substring(begin, str.length()));
            }
        }

        return categories.toArray(new String[0]);
    }
}

Related

  1. splitString(String originalString, String delimeter)
  2. splitString(String source, String delimiter)
  3. splitString(String splitStr, String delim)
  4. splitString(String str, char delim)
  5. splitString(String str, String delim)
  6. splitString(String str, String delims)
  7. splitString(String toSplit, String delimiter)
  8. splitStringList(String strList, String delimit)
  9. splitStringUsingDelimiter(String name, String delimiter)