日期:2014-05-20 浏览次数:20988 次
public static void main(String[] args) throws ParseException { String str = "aa,bb,cc,\"aa,bb,cc\",22,33 "; String[] result = split(str, ','); for (String string : result) { System.out.println(string); } } public static String[] split(String source, char ch) { List<String> values = new ArrayList<String>(); StringBuffer temp = new StringBuffer(); int count = 0; for (int i = 0; i < source.length(); i++) { char currentChar = source.charAt(i); if (currentChar == ch) { if (count == 0) { if (i == 0) { continue; } values.add(temp.toString()); temp = new StringBuffer(); } else { temp.append(currentChar); } } else if (currentChar == '"') { if (count == 0) { count++; } else { count--; } temp.append(currentChar); } else { temp.append(currentChar); } } // if the last string is not blank, trim it and add this value to result if (temp.toString().trim().length() != 0) { values.add(temp.toString().trim()); } String[] result = new String[values.size()]; for (int i = 0; i < values.size(); i++) { result[i] = values.get(i); } return result; }
------解决方案--------------------
改了一下,改正了存在奇数个"分割不正确的问题
public static String[] split(String source, char ch) {
        List<String> values = new ArrayList<String>();
        StringBuffer temp = new StringBuffer();
        int count = 0;
        for (int i = 0; i < source.length(); i++) {
            char currentChar = source.charAt(i);
            if (currentChar == ch) {
                if (count == 0) {
                    if (i == 0) {
                        continue;
                    }
                    values.add(temp.toString());
                    temp = new StringBuffer();
                } else {
                    temp.append(currentChar);
                }
            } else if (currentChar == '"') {
                if (count == 0) {
                    count++;
                } else {
                    count--;
                }
                temp.append(currentChar);
            } else {
                temp.append(currentChar);
            }
        }
        // if the last string is not blank, trim it and add this value to result
        if (temp.toString().trim().length() != 0) {
            if (count != 0) {
                String[] temps = temp.toString().trim().split(",");
                for (String string : temps) {
                    values.add(string);
                }
            } else {
                values.add(temp.toString().trim());
            }
        }
        String[] result = new String[values.size()];
        for (int i = 0; i < values.size(); i++) {
            result[i] = values.get(i);
        }
        return result;
    }