2

Here's my problem : I have this String for instance

[[0,0,1],[1,0,0],[1,1,1]]

And I would like to convert it into an actual

int[][]

What's the best way to proceed ?

Thank you in advance !

bknopper
  • 1,193
  • 12
  • 28
  • 9
    Please post what you've tried so far. Otherwise this will likely be closed. – Peter Bratton Feb 27 '14 at 20:39
  • Luckily, it looks like your String is already in JSON format. JSON is a type of "universal" language. There are standard Java library tools that will convert it for you, but I can't remember what they are. – Rainbolt Feb 27 '14 at 20:42
  • Here a solution to do it with a 1D array. http://stackoverflow.com/questions/456367/reverse-parse-the-output-of-arrays-tostringint. Inspire yourself and adapt the solution to parse a multidimensional array. – Alexis C. Feb 27 '14 at 20:44
  • i've split the string with "," without the first and last char (logical). Then same thing with others, and with loop I may have something but i'm sure there's better. – John Biscuit Feb 27 '14 at 20:44

3 Answers3

2

The string you have is a lot like JSON format. You can use a JSON parser like gson

https://code.google.com/p/google-gson/

It will be able to parse string variants of lots of things.

The default fromJson might work since you are using pretty simple value types, but you can also try to explicitly set the array type.

Type listType = new TypeToken<Integer[][]>() {}.getType();
Integer[][] yourArray = new Gson().fromJson(text, listType);
Ted
  • 3,212
  • 25
  • 20
0

Use nested loops and the Integer.parseInt method.

KyleM
  • 4,445
  • 9
  • 46
  • 78
  • why the downvote? OP never mentioned JSON so I assumed his notation was for a 2D String array. This is a valid method for such a scenario. Downvoting should not even be allowed without a corresponding explanation... – KyleM Feb 27 '14 at 21:28
0

You can ignore the first [ and the last ] as they are not making a difference. The you can split the string by the commas and get a String[]. You just need to iterate through that and fill up your int[][].