Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

parse string to an array in 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"].

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading