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

Here you can find the source of split(final String expression, final char separator)

Description

Splits an expression by the specified separator but keeps track of brackets so separator characters inside of a sub type are ignored.

License

Open Source License

Parameter

Parameter Description
expression The expression to split.
separator The separator character.

Return

The splitted expression parts.

Declaration

public static String[] split(final String expression,
        final char separator) 

Method Source Code

//package com.java2s;
/*/*from w w w .j  a  v a 2 s .c  om*/
 * Copyright (C) 2012 Klaus Reimer <k@ailis.de>
 * See LICENSE.md for licensing information.
 */

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

public class Main {
    /**
     * Splits an expression by the specified separator but keeps track of
     * brackets so separator characters inside of a sub type are ignored. The
     * splitted parts are also trimmed.
     *
     * @param expression
     *            The expression to split.
     * @param separator
     *            The separator character.
     * @return The splitted expression parts.
     */
    public static String[] split(final String expression,
            final char separator) {
        final List<String> parts = new ArrayList<String>();
        int start = 0;
        int level = 0;
        final int len = expression.length();
        for (int i = 0; i < len; i += 1) {
            final char c = expression.charAt(i);
            if (c == separator) {
                if (level == 0) {
                    parts.add(expression.substring(start, i).trim());
                    start = i + 1;
                }
            }
            if (c == '{' || c == '<' || c == '[' || c == '(')
                level += 1;
            else if (c == '}' || c == '>' || c == ']' || c == ')')
                level -= 1;
        }
        if (start <= len)
            parts.add(expression.substring(start, len).trim());
        return parts.toArray(new String[parts.size()]);
    }
}

Related

  1. fastSplit(final String text, char separator)
  2. fastSplit(String text, char separator)
  3. split(byte[] b, int separator)
  4. split(CharSequence seq, char separator)
  5. split(final String input, final String separator)
  6. split(final String iSource, final char iRecordSeparator, final char... iJumpCharacters)
  7. split(final String s, final char separator)
  8. split(final String str, final char separator)