11

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 is thrown:

Exception in thread "main" java.lang.NumberFormatException:
For input string: "" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:592) at java.lang.Integer.parseInt(Integer.java:615) at net.projecteuler.Problem_008Kt.main(Problem_008.kt:54)

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

Willi Mentzel
  • 24,988
  • 16
  • 102
  • 110
abra
  • 578
  • 5
  • 11

3 Answers3

11

Your split("") approach results in [, 1, 2, 3, 4, 5, 6, 7, ], i.e. the first and last element can't be formatted into a number.

Actually, CharSequence.map is all you need:

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

With this code, the single characters of the String are converted into the corresponding Int representation. It results in a List<Int> which can be converted to an array like this:

string.map { it.toString().toInt() }.toIntArray()
s1m0nw1
  • 67,502
  • 14
  • 150
  • 189
6

You just don't need split, but you must also not call toInt() on the character directly; this will give you its Unicode value as an integer. You need Character.getNumericValue():

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

It prints 2.

Marko Topolnik
  • 188,298
  • 27
  • 302
  • 416
4

Like already stated, using map suffices. I just want to add that you should consider the case that your string does not only contain numbers.

This extension function would take care of that:

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

Usage:

val digits = "31w4159".toSingleDigitList()

Result:

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

Willi Mentzel
  • 24,988
  • 16
  • 102
  • 110