2013-02-21 44 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); 
相关问题