Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string with no spaces into array of integers in Kotlin? [duplicate]

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]?

like image 871
abra Avatar asked Feb 08 '18 20:02

abra


Video Answer


3 Answers

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()
like image 128
s1m0nw1 Avatar answered Oct 16 '22 22:10

s1m0nw1


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.

like image 45
Marko Topolnik Avatar answered Oct 16 '22 22:10

Marko Topolnik


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]

like image 4
Willi Mentzel Avatar answered Oct 16 '22 22:10

Willi Mentzel