How can I convert a string to an array of strings in Kotlin? To demonstrate, I have this:
val input_string = "[Hello, World]"
I would like to convert it to ["Hello", "World"].
How can I convert a string to an array of strings in Kotlin? To demonstrate, I have this:
val input_string = "[Hello, World]"
I would like to convert it to ["Hello", "World"].
Assuming that the array elements do not contain commas, you can do:
someString.removeSurrounding("[", "]")
.takeIf(String::isNotEmpty) // this handles the case of "[]"
?.split(", ")
?: emptyList() // in the case of "[]"
This will give you a List<String>. If you want an Array<String>:
someString.removeSurrounding("[", "]")
.takeIf(String::isNotEmpty)
?.split(", ")
?.toTypedArray()
?: emptyArray()
[], you want an empty list/array, not a list with one empty string in it, right?