Java String Split by Separator split(String str, String separator, boolean preserveEmptyToken)

Here you can find the source of split(String str, String separator, boolean preserveEmptyToken)

Description

Split the string into tokens by the specified separator.

License

Apache License

Parameter

Parameter Description
str the string to be split
separator the separator
preserveEmptyToken if set this to true, we preserve all empty tokens

Return

the token array

Declaration

public static final String[] split(String str, String separator, boolean preserveEmptyToken) 

Method Source Code

//package com.java2s;
/**/*  ww  w .  jav  a 2 s .  c  o  m*/
 * StringUtil.java
 *
 * Copyright 2012 Niolex, Inc.
 *
 * Niolex licenses this file to you 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.ArrayList;

import java.util.List;

public class Main {
    /**
     * Split the string into tokens by the specified separator. We will preserve all the empty
     * tokens if you need.
     * <br>
     * This is a replacement of {@link String#split(String)}, which using regex.
     *
     * @param str the string to be split
     * @param separator the separator
     * @param preserveEmptyToken if set this to true, we preserve all empty tokens
     * @return the token array
     */
    public static final String[] split(String str, String separator, boolean preserveEmptyToken) {
        List<String> list = new ArrayList<String>();
        int start = 0, i = 0, len = separator.length(), total = str.length();
        while ((i = str.indexOf(separator, start)) != -1) {
            if (start != i || preserveEmptyToken) {
                list.add(str.substring(start, i));
            }
            start = i + len;
        }
        if (start != total || preserveEmptyToken) {
            list.add(str.substring(start, total));
        }
        return list.toArray(new String[list.size()]);
    }
}

Related

  1. split(String str, char separatorChar)
  2. split(String str, char separatorChar)
  3. split(String str, char separatorChar, boolean preserveAllTokens)
  4. split(String str, String separator)
  5. split(String str, String separator)
  6. split(String string, char separator)
  7. split(String strToSplit, String strSeparator, int iLimit)
  8. split(String text, String separators, String brackets)
  9. splitAll(String str, char separatorChar)