-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?

  • make use of regex to parse the contents of string and then insert them into array – Rishi Mar 10 '16 at 23:57
  • 2
    or you can use json deserialize – libertylocked Mar 10 '16 at 23:58
  • Possible duplicate: [Java convert special string to array of array - Stack Overflow](http://stackoverflow.com/questions/12652135/java-convert-special-string-to-array-of-array) (I voted as too bload before searching...) – MikeCAT Mar 10 '16 at 23:58

2 Answers2

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);
}
-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));
Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102
  • 1
    Seems fragile. What if there are escaped special characters in the strings? Better to use a JSON parser. – Thilo Mar 11 '16 at 00:01