Reputation: 10996
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"]
.
Upvotes: 3
Views: 1318
Reputation: 23154
Assuming the strings only consist of letters and/or numbers you could also do it like this
val input_string = "[Hello, World]"
val list = Regex("\\w+").findAll(input_string).toList().map { it.value }
Upvotes: 1
Reputation: 270980
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()
Upvotes: 4