Reputation: 5697
I have a string in Java like this:
String s = "{{\"2D\", \"array\"}, {\"represented\", \"in a string\"}}"
How can I convert it into an actual array? Like so:
String[][] a = {{"2D", "array"}, {"represented", "in a string"}}
(What I'm looking for is a solution a bit like python's eval()
)
Upvotes: 5
Views: 1754
Reputation: 32391
I strongly suggest that you use a json capable library to parse your String
. However, just for fun, please take a look at the code below, that does the thing you need using only String
methods:
String s = "{{\"2D\", \"array\"}, {\"represented\", \"in a string\"}}";
s = s.replace("{", "");
String[] s0 = s.split("},\\s");
int length = s0.length;
String[][] a = new String[length][];
for (int i = 0; i < length; i++) {
a[i] = s0[i].replace("}", "").split(",\\s");
}
Upvotes: 3