I´m looking for the most efficient way to convert an String like
"[1,2,3,4,5]"
to an array of Int [1,2,3,4,5]
in Kotlin
IntArray is a class in Kotlin representing the array of elements. Each instance of this class is represented as an integer array. To the constructor of this class you need to pass the number of elements you need in the array (size). By default, all the elements of the created array will be initialized to "0".
The joinToString() function is used to convert an array or a list to a string which is separated with the mentioned separator. In the example above, I am using joinToString() to convert the list of Kotlin data classes into a comma separated string.
Fortunately I've been able to make it work, so I'll leave it here for future reference
val result = "[1,2,3,4,5]".removeSurrounding("[", "]").split(",").map { it.toInt() }
Many thanks to all!
When user convert list to string and again need that string to list. Due to space between integer app crashes with NumberFormatException for that just remove unnecessary space.
val result = "[1, 2, 3, 4, 5]".removeSurrounding("[","]").replace(" ","").split(",").map { it.toInt() }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With