2013-02-21 81 views
0
5163583,601028,30,,0,"Leaflets, samples",Cycle 5 objectives,,20100804T071410, 

如何將字符串轉換爲長度爲10的數組? 我期望的陣列是:如何將字符串拆分爲java中長度爲10的數組?

array[0]="5163583"; 
array[1]="601028"; 
array[2]="30"; 
array[3]=""; 
array[4]="0"; 
array[5]="Leaflets, samples"; 
array[6]="Cycle 5 objectives"; 
array[7]=""; 
array[8]="20100804T071410"; 
array[9]=""; 

非常感謝!

+1

請用更容易理解的方式提出您的問題。最上面那個長串的東西是什麼? – 2013-02-21 05:43:20

+1

通過java.lang.String庫類。有很多方法來解析字符串[oracle鏈接](http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html) – 2013-02-21 05:46:17

+0

通過你的邏輯,'array [5] =「傳單,樣本」;'應該更多地沿着'數組[5] =「\」單頁,樣本\「」;' – 2013-02-21 05:47:51

回答

1
String string = 
    "5163583,601028,30,,0,\"Leaflets, samples\",Cycle 5 objectives,,20100804T071410,"; 

Matcher m = Pattern.compile ("(\"[^\"]*\"|[^,\"]*)(?:,|$)").matcher (string); 

List <String> chunks = new ArrayList <String>(); 
while (m.find()) 
{ 
    String chunk = m.group (1); 
    if (chunk.startsWith ("\"") && chunk.endsWith ("\"")) 
     chunk = chunk.substring (1, chunk.length() - 1); 
    chunks.add (chunk); 
} 

String array [] = chunks.toArray (new String [chunks.size()]); 
for (String s: array) 
    System.out.println ("'" + s + "'"); 
+0

此解決方案的一個潛在問題是,它假設報價從不出現在引用字符串中(轉義報價未考慮在內)。 (順便說一下,爲什麼在函數調用的參數之前添加一個空格?)。 – nhahtdh 2013-02-21 06:07:17

+0

@nhahtdh這是一個問題,但缺少易於添加的功能。 – 2013-02-21 06:37:11

3

您正在尋找CSV閱讀器。您可以使用opencsv

隨着opencsv庫:

new CSVReader(new StringReader(inputString)).readNext() 

它返回列值的陣列。

0
String sb = "5163583,601028,30,,0,\"Leaflets, samples\",Cycle 5 objectives,,20100804T071410,"; 

String[] array = new String[10]; 
StringBuilder tmp = new StringBuilder(); 
int count=0; 
for(int i=0, index=0; i<sb.length(); i++) 
{ 
    char ch = sb.charAt(i); 
    if(ch==',' && count==0) 
    { 
     array[index++] = tmp.toString(); 
     tmp = new StringBuilder(); 
     continue; 
    } 
    else if(ch=='"') 
    { 
     count = count==0 ? 1 : 0; 
     continue; 
    } 

    tmp.append(ch); 
} 
for(String s : array) 
    System.out.println(s); 
相關問題