Java String Split splitArguments(String arguments)

Here you can find the source of splitArguments(String arguments)

Description

split Arguments

License

Apache License

Declaration

public static String[] splitArguments(String arguments) 

Method Source Code

//package com.java2s;
/*//w w  w  . ja  va2 s.c o m
 * Copyright 2000-2015 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.util.ArrayList;

public class Main {
    public static String[] splitArguments(String arguments) {
        boolean inQuotes = false;
        ArrayList<String> arrayList = new ArrayList<String>();
        int firstChar = 0;
        int i;
        char ch;
        for (i = 0; i < arguments.length(); i++) {
            ch = arguments.charAt(i);
            if (ch == '\\' && arguments.charAt(i + 1) == '\"') {
                i++;
                continue;
            }
            if (ch == '\"') {
                inQuotes = !inQuotes;
            }
            if (ch == ' ') {
                if (!inQuotes) {
                    arrayList.add(arguments.substring(firstChar, i));
                    firstChar = i + 1;
                }
            }
        }

        if (firstChar != arguments.length()) {
            arrayList.add(arguments.substring(firstChar, arguments.length()));
        }

        String[] result = new String[arrayList.size()];

        int j = 0;
        for (String element : arrayList) {
            element = element.replaceAll("\\\\\"", "QUOTE");
            element = element.replaceAll("\"", "");
            element = element.replaceAll("QUOTE", "\\\\\"");
            result[j] = element;
            j++;
        }
        return result;
    }
}

Related

  1. splitAndTrim(String str)
  2. splitAndTrim(String str, String splitBy)
  3. splitAndUnEscape(String str)
  4. splitArgs(String args, int expectedArgs)
  5. splitArguments(final String str)
  6. splitArguments(String s)
  7. splitArguments(String str)
  8. splitArguments(String string)
  9. splitArguments(String string)