2013-10-10 46 views
-3

我试图分裂的字符串例如分割一个字符串(以前的代码),我想分开int和字符串的|字符串包含

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

+2

你有什么尝试。有什么问题? –

+0

请问你能更具体吗? – burntsugar

+0

有什么不清楚吗?他想要在单引号内部的逗号分割,并且放弃单引号。所以单引号将字符串值1,2,2'转换成一个单位,这个单位不会在逗号处被分开;而'0,10,20'等之间的逗号会导致分割。多么可惜,我无法给出答案。 –

回答

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) + "\""); 
    } 

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