0

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?

6
  • 2
    That's not a valid string because it's enclosed in single quotes. Commented Oct 22, 2010 at 20:13
  • As in a quick one-liner method? the Java Programming language isn't big on those. You'd have to do some work. Furthermore, strings aren't valid in '' in Java. Now, if you're thinking of Javascript, you're asking a different question. Commented Oct 22, 2010 at 20:13
  • no. it's not java. actually, it is a string from SAS. but Java programs needs [][], so I have to convert it. thanks! Commented Oct 22, 2010 at 20:17
  • 1
    Furthermore, if you're working in Java, are you sure you want a 2D string and not a HashMap? Or to write a class that encapsulates what obviously seem to be fields, and then have another method that parses your data and uses instances of those classes? Commented Oct 22, 2010 at 20:18
  • If it's not Java, how would you ever convert it using Java? :) Commented Oct 22, 2010 at 20:24

3 Answers 3

3
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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.