How do I convert a Char to Int?

ibroadsword picture ibroadsword · Dec 1, 2017 · Viewed 15.7k times · Source

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?

Answer

s1m0nw1 picture s1m0nw1 · Dec 1, 2017

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)