How to split a string without spaces into an array of integers in Kotlin?

I need to split a string into an array of integers. I tried this:

val string = "1234567"
val numbers = string.split("").map { it.toInt() }
println(numbers.get(1))

but the following exception:

An exception in the stream "main" java.lang.NumberFormatException:
For the input line: "" at java.lang.NumberFormatException.forInputString (NumberFormatException.java:65) in java.lang.Integer.parseInt (Integer.java∗92) at java .lang.Integer.parseInt (Integer.java:615) in net.projecteuler.Problem_008Kt.main (Problem_008.kt: 54)

How to convert the string "123456" to an array [1,2,3,4,5,6]?

+6
source share
3 answers

split("") [, 1, 2, 3, 4, 5, 6, 7, ], .. .

, CharSequence.map - , :

val numbers = string.map { it.toString().toInt() } //[1, 2, 3, 4, 5, 6, 7]

String Int. List<Int>, :

string.map { it.toString().toInt() }.toIntArray()
+4

split, toInt() ; Unicode . Character.getNumericValue():

val string = "1234567"
val digits = string.map(Character::getNumericValue).toIntArray()
println(digits[1])

2.

+4

, . , , .

:

fun String.toSingleDigitList() = map {
    "$it".toIntOrNull()
}.filterNotNull()

:

val digits = "31w4159".toSingleDigitList()

:

[3, 1, 4, 1, 5, 9]

+1

All Articles