12

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

heisen
  • 1,067
  • 3
  • 9
  • 25
  • Duplicate of https://stackoverflow.com/questions/45823162/how-to-convert-string-array-to-int-array-in-kotlin – Julian Rubin Nov 19 '17 at 23:38
  • in the JavaScript version `JSON.parse>("[1,2,3,4,5]")` – Slai Nov 19 '17 at 23:41
  • Hi Julian, the question you suggest as duplicated refers to an array of Strings, and clearly is not the case here. This question is about only one String, containing and array of Int – heisen Nov 19 '17 at 23:45
  • 1
    For better understanding, here is a question asking for the same case, but in Java https://stackoverflow.com/questions/7646392/convert-string-to-int-array-in-java – heisen Nov 19 '17 at 23:49
  • [This answer](https://stackoverflow.com/a/25839398/3195526) to the above question is pretty easy to translate to idionmatic Kotlin. Or use klaxon or JSONObject, for an answer like @Slai's – Paul Hicks Nov 19 '17 at 23:59

4 Answers4

20

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!

heisen
  • 1,067
  • 3
  • 9
  • 25
3

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() }
Rahul Khatri
  • 1,502
  • 2
  • 13
  • 25
0

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

See more in the kotlin webpage

Alex
  • 85
  • 1
  • 8
0

Also another way to achieve this:

"[1,2,3,4,5]".replace(Regex("""[\[,\]]"""), "").map { it - '0' }
gce
  • 1,563
  • 15
  • 17