-2

This might have been asked before, but I spent some time looking, so here's what I have. I have a string containing an array:

'["thing1","thing2"]'

I would like to convert it into an actual array:

["thing1","thing2"]

How would I do this?

3
  • make use of regex to parse the contents of string and then insert them into array Commented Mar 10, 2016 at 23:57
  • 2
    or you can use json deserialize Commented Mar 10, 2016 at 23:58
  • Possible duplicate: Java convert special string to array of array - Stack Overflow (I voted as too bload before searching...) Commented Mar 10, 2016 at 23:58

2 Answers 2

0

You could create a loop that runs through the whole string, checking for indexes of quotes, then deleting them, along with the word. I'll provide an example:

ArrayList<String> list = new ArrayList<String>();
while(theString.indexOf("\"") != -1){
    theString = theString.substring(theString.indexOf("\"")+1, theString.length());
    list.add(theString.substring(0, theString.indexOf("\"")));
    theString = theString.substring(theString.indexOf("\"")+1, theString.length());
}

I would be worried about an out of bounds error from looking past the last quote in the String, but since you're using a String version of an array, there should always be that "]" at the end. But this creates only an ArrayList. If you want to convert the ArrayList to a normal array, you could do this afterwards:

String[] array = new String[list.size()];
for(int c = 0; c < list.size(); c++){
    array[c] = list.get(c);
}
Sign up to request clarification or add additional context in comments.

Comments

-1

You can do it using replace and split methods of String class, e.g.:

String s = "[\"thing1\",\"thing2\"]";
String[] split = s.replace("[", "").replace("]", "").split(",");
System.out.println(Arrays.toString(split));

1 Comment

Seems fragile. What if there are escaped special characters in the strings? Better to use a JSON parser.

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.