How to convert char to int?

So, I have Stringintegers that look like "82389235", but I wanted to iterate it to add each number separately to MutableList. However, when I get around this, I think it will be handled:

var text = "82389235"

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

This adds numbers not completely associated with the line in the list. However, if I use printlnto output it to the console, it does an excellent iteration of the line.

How to convert Charto Int?

+4
source share
3 answers

This is because it numis Char, that is, the resulting values ​​are the ascii value of this char.

This will do the trick:

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

map can even be simplified as follows:

map(Character::getNumericValue)
+3

num Char. toInt() ASCII , .

, ASCII 0 :

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

:

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

map, MutableList:

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

String, String.toInt() - :

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

JVM java.lang.Character.getNumericValue():

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

Source: https://habr.com/ru/post/1690124/


All Articles