john
john

Reputation: 2662

How to convert a String into a String[][]

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?

Upvotes: 0

Views: 193

Answers (3)

Carl
Carl

Reputation: 7544

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.

Upvotes: 3

Michael Bazos
Michael Bazos

Reputation: 11

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.

Upvotes: 0

duffymo
duffymo

Reputation: 308743

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

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

Upvotes: 0

Related Questions