Java String Split by Delimiter fastSplit(String string, char delimiter)

Here you can find the source of fastSplit(String string, char delimiter)

Description

Splits a String based on a single character, which is usually faster than regex-based String.split().

License

Apache License

Declaration

public static String[] fastSplit(String string, char delimiter) 

Method Source Code

//package com.java2s;
/*/*w w w . java 2 s  .c  o  m*/
 * Copyright (C) 2014 Markus Junginger, greenrobot (http://greenrobot.de)
 *
 * 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.ArrayList;

import java.util.List;

public class Main {
    /** Splits a String based on a single character, which is usually faster than regex-based String.split(). */
    public static String[] fastSplit(String string, char delimiter) {
        List<String> list = new ArrayList<String>();
        int size = string.length();
        int start = 0;
        for (int i = 0; i < size; i++) {
            if (string.charAt(i) == delimiter) {
                if (start < i) {
                    list.add(string.substring(start, i));
                } else {
                    list.add("");
                }
                start = i + 1;
            } else if (i == size - 1) {
                list.add(string.substring(start, size));
            }
        }
        String[] elements = new String[list.size()];
        list.toArray(elements);
        return elements;
    }
}

Related

  1. fastSplit(String string, String delimiter)
  2. split(final boolean enable, final String value, final char delimiter)
  3. split(final String input, final char delimiter)
  4. split(final String input, final String delimiter, final boolean removeEmpty)