Luca
Luca

Reputation: 10996

Parsing a string of array of arrays

I have a string input of the following format:

[[10.5,125.7], [60.5, 25.6] ....]]

How can one parse something like this in Kotlin? This should end up as array of arrays of floats.

Upvotes: 0

Views: 167

Answers (1)

lukas.j
lukas.j

Reputation: 7163

For a List<List<Float>>:

val result = text
  .removeSurrounding("[[", "]]").split("], [", "],[")
  .map { it.split(",").map { s -> s.toFloat() } }

For an Array<Array<Float>>:

val result = text
  .removeSurrounding("[[", "]]").split("], [", "],[")
  .map { it.split(",").map { s -> s.toFloat() }.toTypedArray() }
  .toTypedArray()

Upvotes: 2

Related Questions