TMH
TMH

Reputation: 6246

Android convert String to String[]

I have a String

["first","second","third"]

And I need to convert it to a String[] so I can loop through it.

I've seen people suggest

String[] mArray = {mString};

But that doesn't work for me, do I need to format my String differently first before converting it?

Upvotes: 0

Views: 12393

Answers (2)

Maximin
Maximin

Reputation: 1685

You can make use of split method in String class.

If you wanna do that

1) remove all "
2) take substring inorder to remove the [ and ]
3) Then make use of split method.

Sample Code

String tmp="[\"first\",\"second\",\"third\"]".replace("\"", "");
String tm[]=tmp.substring(1, tmp.length()-1).split(",");
for(int i=0;i<tm.length;i++)
System.out.println(tm[i]);

Upvotes: 2

rachit
rachit

Reputation: 1996

use this code

JSONArray temp = new JSONArray(mString);
String[] mArray = temp.join(",").split(",");

Upvotes: 7

Related Questions