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

Luca
  • 10,458
  • 24
  • 107
  • 234

2 Answers2

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()
Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • Are you sure you need the step with _takeIf_ (and _?: emptyList()_)? – lukas.j Feb 08 '22 at 10:47
  • @lukas.j Yes. For the input string `[]`, you want an empty list/array, not a list with one empty string in it, right? – Sweeper Feb 08 '22 at 10:48
  • Of course, you're right (almost every time I come back to Kotlin I stumble across the _split_ specialities...). – lukas.j Feb 08 '22 at 10:49
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 }
Ivo
  • 18,659
  • 2
  • 23
  • 35