拆分字符串(以前的代码),我要分隔int和字符串的|字符串包含分隔符

时间:2013-10-10 21:57:50

标签: java string

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

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“。

1 个答案:

答案 0 :(得分: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) + "\"");
    }

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