Java String Split by Separator split(final T string, final char separator)

Here you can find the source of split(final T string, final char separator)

Description

split

License

Open Source License

Declaration

@SuppressWarnings("unchecked")
    static <T extends CharSequence> ArrayList<T> split(final T string, final char separator) 

Method Source Code

//package com.java2s;
/*//  w  w w  .jav a2s.  c  om
 * The MIT License
 *
 * Copyright 2014 Karol Bucek.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

import java.util.ArrayList;

public class Main {
    @SuppressWarnings("unchecked")
    static <T extends CharSequence> ArrayList<T> split(final T string, final char separator) {
        final ArrayList<T> split = new ArrayList<T>(8);
        int last = 0;
        for (int i = 0; i < string.length(); i++) {
            if (string.charAt(i) == separator) {
                split.add((T) string.subSequence(last, i));
                last = ++i;
            }
        }
        if (last == 0)
            split.add(string); // split.isEmpty
        else
            split.add((T) string.subSequence(last, string.length()));
        return split;
    }

    public static String[] split(final String string, final char separator) {
        final ArrayList<CharSequence> split = split((CharSequence) string, separator);
        return split.toArray(new String[split.size()]);
    }
}

Related

  1. split(final String str, final char separatorChar)
  2. split(final String str, final char separatorChar)
  3. split(final String str, final char[] separators)
  4. split(final String text, final char separator)
  5. split(final String text, final String separator)
  6. split(String array, String separators)
  7. split(String input, int separator)
  8. split(String left, String separator)
  9. split(String s, char separator)