13

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

5
  • Duplicate of stackoverflow.com/questions/45823162/… Commented Nov 19, 2017 at 23:38
  • in the JavaScript version JSON.parse<Array<Int>>("[1,2,3,4,5]") Commented Nov 19, 2017 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 Commented Nov 19, 2017 at 23:45
  • 1
    For better understanding, here is a question asking for the same case, but in Java stackoverflow.com/questions/7646392/… Commented Nov 19, 2017 at 23:49
  • This answer to the above question is pretty easy to translate to idionmatic Kotlin. Or use klaxon or JSONObject, for an answer like @Slai's Commented Nov 19, 2017 at 23:59

4 Answers 4

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!

Sign up to request clarification or add additional context in comments.

1 Comment

Competitive programming? Either way, thanks.
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() }

3 Comments

simply call it.trim().toInt() to remove empty spaces
@RichardMuvirimi Can one not specify 2 characters in split? As in List.split(",\ ")
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

Comments

0

Also another way to achieve this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.