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

其他可能有一個更優雅的解決方案。祝你好運!