Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin String to Int array

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

like image 925
heisen Avatar asked Nov 19 '17 23:11

heisen


People also ask

How do I return an int array 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".

What is joinToString?

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.


2 Answers

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!

like image 51
heisen Avatar answered Oct 16 '22 19:10

heisen


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() }
like image 29
Rahul Khatri Avatar answered Oct 16 '22 18:10

Rahul Khatri