Java String Split by Space splitAndKeepEscapedSpaces(String string, boolean preserveEscapes)

Here you can find the source of splitAndKeepEscapedSpaces(String string, boolean preserveEscapes)

Description

split And Keep Escaped Spaces

License

Open Source License

Declaration

public static String[] splitAndKeepEscapedSpaces(String string, boolean preserveEscapes) 

Method Source Code

//package com.java2s;
/**/*from  w w  w  .j a  v a 2 s.c o  m*/
 * Copyright (c) 2002-2014 "Neo Technology,"
 * Network Engine for Objects in Lund AB [http://neotechnology.com]
 *
 * This file is part of Neo4j.
 *
 * Neo4j 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.Collection;

public class Main {
    public static String[] splitAndKeepEscapedSpaces(String string, boolean preserveEscapes) {
        Collection<String> result = new ArrayList<String>();
        StringBuilder current = new StringBuilder();
        for (int i = 0; i < string.length(); i++) {
            char ch = string.charAt(i);
            if (ch == ' ') {
                boolean isGluedSpace = i > 0 && string.charAt(i - 1) == '\\';
                if (!isGluedSpace) {
                    result.add(current.toString());
                    current = new StringBuilder();
                    continue;
                }
            }

            if (preserveEscapes || ch != '\\') {
                current.append(ch);
            }
        }
        if (current.length() > 0) {
            result.add(current.toString());
        }
        return result.toArray(new String[result.size()]);
    }
}

Related

  1. split(String source, String limit, boolean trim, boolean ignoreWhitespace)
  2. splitAtSpaces(String s)
  3. splitBySpace(String p_str)
  4. splitInWhiteSpaces(String string)
  5. splitNamespaceTitle(String fullTitle)