views:

122

answers:

3

I have a string like this:

String string ='{{"INPUT FILE", "NUMBER OF RECORDS"},{"Item File", "11,559"},{"Vendor File", "300"}, {"Purchase History File", "10,000"},{"Total # of requisitions", "10,200,038"}}';

And I want to convert it into an array like this:

String [][] data = {
          {"INPUT FILE", "NUMBER OF RECORDS"},
          {"Item File", "11,559"},
          {"Vendor File", "300"},
          {"Purchase History File", "10,000"},
          {"Total # of requisitions", "10,200,038"}
      };

How could I do that?

A: 

You'll have to parse it with a 2D array in mind.

Start with the rows (delimited by "},"), then break those into values.

duffymo
A: 

write a method and use StringUtils http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/StringUtils.html use one of the split* methods in StringUtils. You will need to run the split* method twice since you have a two dimensional array.

Michael Bazos
+3  A: 
String[] first = string.replaceAll("[({{\")(\"}})]","").split("\"},{\"");
String[][] result = new String[first.length][];
for (int i=0; i<first.length; i++)
  result[i] = first[i].split("\", \"");

I think that's about right - there may be some fiddly bits with escaped characters.

Fixed some problems with splits on the commas in the numbers.

Note, this is super fragile and totally dependent on the format you provided.

Carl