Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 416
ibroadsword Avatar asked Dec 01 '17 11:12

ibroadsword


People also ask

Can we change char to int in Java?

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.

How do I convert a char to an int in R?

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.


2 Answers

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) 
like image 97
s1m0nw1 Avatar answered Sep 21 '22 09:09

s1m0nw1


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

val numbers: List<Int> = "82389235".map(Character::getNumericValue) 
like image 27
Vadzim Avatar answered Sep 19 '22 09:09

Vadzim