3

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

1

2 Answers 2

4

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()
Sign up to request clarification or add additional context in comments.

3 Comments

Are you sure you need the step with takeIf (and ?: emptyList())?
@lukas.j Yes. For the input string [], you want an empty list/array, not a list with one empty string in it, right?
Of course, you're right (almost every time I come back to Kotlin I stumble across the split specialities...).
1

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 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.