-3

例如,我正在尝试拆分字符串

String line = "(0, 10, 20, 'string value, 1, 2, 2', 100, 'another string', 'string, string, text', 0)";

我想让它拆分,所以我会有“0”、“10”、“20”、“字符串值、1、2、2”等等,而不是“0”、“10”、“20”, “'字符串值”、“1”、“2”、“2”。

4

1 回答 1

1

如果我正确理解了您的问题(尝试更具体:))您希望拆分字符串以实现以下输出:

"0","10","20","string value, 1, 2, 2","100","another string","string, string, text","0"

我很想尝试一下,所以这里是:

String line = "(0, 10, 20, 'string value, 1, 2, 2', 100, 'another string', 'string, string, text', 0)";
    char splitString[] = line.toCharArray();
    List<String> foundStrings = new ArrayList<String>();
    for (int x = 0; x < splitString.length;x++){
        String found = "";
        if (Character.isDigit(splitString[x])) {
            while(Character.isDigit(splitString[x])) {
                found += Character.toString(splitString[x]);
                x++;
            }
            foundStrings.add(found);
            x --;
        }
        if (x < splitString.length) {
            int count = 0;
            int indexOfNext = 0;
            if (splitString[x] == '\'') {
                int startIndex = x + 1;
                count = startIndex;
                char currentChar = 0;
                char c = '\'';
                while(currentChar != c) {
                    currentChar = splitString[count];
                    count ++;
                    currentChar = splitString[count];
                }
                indexOfNext = count;
                for (int j = startIndex; j < indexOfNext; j++){
                    found += Character.toString(splitString[j]);
                }
                foundStrings.add(found.trim());
                x = indexOfNext;
            }
        }
    }
    for (int p = 0; p < foundStrings.size();p++) {
        if (p > 0) System.out.print(",");
        System.out.print("\"" + foundStrings.get(p) + "\"");
    }

其他人可能有更优雅的解决方案。祝你好运!

于 2013-10-11T01:35:34.110 回答