Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parse string to an array in Kotlin

Tags:

kotlin

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

like image 598
Luca Avatar asked Apr 18 '26 11:04

Luca


1 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()
like image 182
Sweeper Avatar answered Apr 21 '26 01:04

Sweeper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!