parse string to an array in Kotlin

Viewed 258

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"].

2 Answers

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()

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 }
Related