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
?
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)
On JVM there is efficient java.lang.Character.getNumericValue() available:
val numbers: List<Int> = "82389235".map(Character::getNumericValue)
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())