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
?
In Java, we can convert the Char to Int using different approaches. If we direct assign char variable to int, it will return the ASCII value of a given character. If the char variable contains an int value, we can get the int value by calling Character. getNumericValue(char) method.
Convert a Character Object to Integer in R Programming – as. integer() Function. as. integer() function in R Language is used to convert a character object to integer object.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With