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
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
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() }
Try with toCharArray() cutting first and last ( '[' and ']' )
inline fun String.toCharArray(
destination: CharArray,
destinationOffset: Int = 0,
startIndex: Int = 1,
endIndex: Int = length -1
): CharArray (source)
You can then manually copy converted values from char to int in a new array
Also another way to achieve this:
"[1,2,3,4,5]".replace(Regex("""[\[,\]]"""), "").map { it - '0' }