Java String Split by Char safeSplit(String string, char divider)

Here you can find the source of safeSplit(String string, char divider)

Description

safe Split

License

Open Source License

Declaration

public static List<String> safeSplit(String string, char divider) 

Method Source Code

//package com.java2s;
/*// ww  w  .  java  2  s  .  c om
 * Copyright (c) Erasmus MC
 *
 * This file is part of TheMatrix.
 *
 * TheMatrix is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

import java.util.ArrayList;

import java.util.List;

public class Main {
    public static List<String> safeSplit(String string, char divider) {

        List<String> result = new ArrayList<String>();

        if (string.length() == 0) {

            result.add("");

            return result;

        }

        boolean literal = false;

        boolean escape = false;

        int startpos = 0;

        int i = 0;

        char currentchar;

        while (i < string.length()) {

            currentchar = string.charAt(i);

            if (currentchar == '"') {
                literal = !literal;
            }

            if (!literal && (currentchar == divider && !escape)) {

                result.add(string.substring(startpos, i));

                startpos = i + 1;

            }

            if (currentchar == '\\') {
                escape = !escape;
            } else {
                escape = false;
            }

            i++;

        }

        //if (startpos != i){

        result.add(string.substring(startpos, i));

        //}

        return result;

    }
}

Related

  1. fastSplit(final String string, final char sep)
  2. fastSplitTrimmed(final String string, final char sep)
  3. split(char c, String s)
  4. split(char elem, String orig)
  5. split(char sep, String input)
  6. split(final String input, final char split)