0
5163583,601028,30,,0,"Leaflets, samples",Cycle 5 objectives,,20100804T071410,

如何将字符串变成长度为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]="";

非常感谢!

4

3 回答 3

3

您正在寻找 CSV 阅读器。您可以使用opencsv

使用 opencsv 库:

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

它返回一个列值数组。

于 2013-02-21T06:01:09.407 回答
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 + "'");
于 2013-02-21T05:42:01.923 回答
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);
于 2013-02-21T06:13:51.403 回答