Issue
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"]
.
Solution
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()
Answered By - Sweeper
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.