5

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())

11
  • Maybe you could regard it as a JSON input. Take a look at this code.google.com/p/google-gson Maybe there's a way to parse string objects. Commented Oct 27, 2012 at 11:54
  • @broncoAbierto: It's not in JSON format, arrays in JSON use [...], not {...}. If it's really as simple as shown, of course the OP could do a replaceAll first to change those over, but it's probably not actually as simple as shown. Commented Oct 27, 2012 at 11:55
  • 3
    The real question is, what situation are you running into that requires you to do this? Commented Oct 27, 2012 at 11:57
  • 3
    ... and what have you tried so far that isn't working? I'm surprised a question that shows no research effort at all is getting so many up-votes. Commented Oct 27, 2012 at 11:59
  • 1
    Your example makes no sense. You declare a String[] and initialize it with String[][]. If you don't know in advance the dimensionality of your array, this is not a simple problem at all. Commented Oct 27, 2012 at 12:02

1 Answer 1

3

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");
}
Sign up to request clarification or add additional context in comments.

1 Comment

Where this will fail is any { or } occuring in the strings.

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.