Here you can find the source of splitQuotedString(String str)
Parameter | Description |
---|---|
str | The string to split. |
static public List<String> splitQuotedString(String str)
//package com.java2s; //License from project: Open Source License import java.util.ArrayList; import java.util.List; public class Main { /**/*from w w w.j a v a 2s .c o m*/ * Splits a string based on spaces, grouping atoms if they are inside non escaped double quotes. * * @param str The string to split. * @return The list of split strings. */ static public List<String> splitQuotedString(String str) { List<String> strings = new ArrayList<String>(); int level = 0; StringBuffer buffer = new StringBuffer(); for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (c == '"') { if (i == 0 || str.charAt(i - 1) == ' ') { // start quote level++; // don't need to append quotes for top-level things if (level == 1) continue; } if (i == str.length() - 1 || str.charAt(i + 1) == ' ' || str.charAt(i + 1) == '"') { // end quote level--; if (level == 0) continue; } } //Peek at the next character - if we have a \", we need to only insert a " if (c == '\\' && i < str.length() - 1 && str.charAt(i + 1) == '"') { c = '"'; i++; } if (level == 0 && str.charAt(i) == ' ') { // done with this part if (buffer.length() > 0) { strings.add(buffer.toString()); buffer.setLength(0); } } else { buffer.append(c); } } //Add on the last string if needed if (buffer.length() > 0) { strings.add(buffer.toString()); } return strings; } }