Java String Split by Char split(final String string, final char... toSplit)

Here you can find the source of split(final String string, final char... toSplit)

Description

Splits some string given many chars

License

Common Public License

Declaration

public static List<String> split(final String string, final char... toSplit) 

Method Source Code


//package com.java2s;
/*//from www.ja v a  2 s .  c o  m
 * @author Fabio Zadrozny
 * Created: June 2005
 * License: Common Public License v1.0
 */

import java.util.ArrayList;
import java.util.List;

public class Main {
    /**
     * Splits some string given many chars
     */
    public static List<String> split(final String string, final char... toSplit) {
        final ArrayList<String> ret = new ArrayList<String>();
        final int len = string.length();

        int last = 0;

        char c = 0;

        for (int i = 0; i < len; i++) {
            c = string.charAt(i);

            if (contains(c, toSplit)) {
                if (last != i) {
                    ret.add(string.substring(last, i));
                }
                while (contains(c, toSplit) && i < len - 1) {
                    i++;
                    c = string.charAt(i);
                }
                last = i;
            }
        }
        if (!contains(c, toSplit)) {
            if (last == 0 && len > 0) {
                ret.add(string); // it is equal to the original (no dots)

            } else if (last < len) {
                ret.add(string.substring(last, len));

            }
        }
        return ret;
    }

    private static boolean contains(final char c, final char[] toSplit) {
        for (final char ch : toSplit) {
            if (c == ch) {
                return true;
            }
        }
        return false;
    }
}

Related

  1. safeSplit(String string, char divider)
  2. split(char c, String s)
  3. split(char elem, String orig)
  4. split(char sep, String input)
  5. split(final String input, final char split)
  6. split(String cs, char sep)
  7. split(String s, char c)
  8. split(String s, char c)
  9. split(String s, char c)