Convert String ["Scenario 1", "Scenario 2"] to Array

sirdaiz :

I have the following code:

String text = "[\"Scenario 1\", \"Scenario 2\"]"

I need to convert "text" to Array. I know that I can replace [ ] " and I do a split(",") but is there a way easy?

Karol Dowbecki :

If you know that the text is well formatted you can use String.substring() instead of regex.

String text = "['Stack1', 'Stack2']";
StringTokenizer tkn = new StringTokenizer(text.substring(1, text.length() - 1), ", ");
while (tkn.hasMoreTokens()) {
    String v = tkn.nextToken();
    System.out.println(v.substring(1, v.length() - 1)); // Stack1 Stack2
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=143336&siteId=1