'How do I convert a Char to Int?

So I have a String of integers that looks like "82389235", but I wanted to iterate through it to add each number individually to a MutableList. However, when I go about it the way I think it would be handled:

var text = "82389235"

for (num in text) numbers.add(num.toInt())

This adds numbers completely unrelated to the string to the list. Yet, if I use println to output it to the console it iterates through the string perfectly fine.

How do I properly convert a Char to an Int?



Solution 1:[1]

That's because num is a Char, i.e. the resulting values are the ascii value of that char.

This will do the trick:

val txt = "82389235"
val numbers = txt.map { it.toString().toInt() }

The map could be further simplified:

map(Character::getNumericValue)

Solution 2:[2]

The variable num is of type Char. Calling toInt() on this returns its ASCII code, and that's what you're appending to the list.

If you want to append the numerical value, you can just subtract the ASCII code of 0 from each digit:

numbers.add(num.toInt() - '0'.toInt())

Which is a bit nicer like this:

val zeroAscii = '0'.toInt()
for(num in text) {
    numbers.add(num.toInt() - zeroAscii)
}

This works with a map operation too, so that you don't have to create a MutableList at all:

val zeroAscii = '0'.toInt()
val numbers = text.map { it.toInt() - zeroAscii }

Alternatively, you could convert each character individually to a String, since String.toInt() actually parses the number - this seems a bit wasteful in terms of the objects created though:

numbers.add(num.toString().toInt())

Solution 3:[3]

On JVM there is efficient java.lang.Character.getNumericValue() available:

val numbers: List<Int> = "82389235".map(Character::getNumericValue)

Solution 4:[4]

Since Kotlin 1.5, there's a built-in function Char.digitToInt(): Int:

println('5'.digitToInt()) // 5 (int)

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/digit-to-int.html

Solution 5:[5]

For clarity, the zeroAscii answer can be simplified to

val numbers = txt.map { it - '0' }

as Char - Char -> Int. If you are looking to minimize the number of characters typed, that is the shortest answer I know. The

val numbers = txt.map(Character::getNumericValue)

may be the clearest answer, though, as it does not require the reader to know anything about the low-level details of ASCII codes. The toString().toInt() option requires the least knowledge of ASCII or Kotlin but is a bit weird and may be most puzzling to the readers of your code (though it was the thing I used to solve a bug before investigating if there really wasn't a better way!)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Vadzim
Solution 3 Salem
Solution 4 Seonghyeon Cho
Solution 5 Eric-Wubbo Lameijer