如何将Char转换为Int?
问题描述:
所以我有一个String
整数,看起来像"82389235"
,但是我想遍历它,将每个数字分别加到MutableList
上.但是,当我按照自己认为的方式进行处理时:
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())
这会将与字符串完全无关的数字添加到列表中.但是,如果我使用println
将其输出到控制台,它会很好地遍历字符串.
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.
如何正确地将Char
转换为Int
?
答
这是因为num
是Char
,即结果值是该char的ascii值.
That's because num
is a Char
, i.e. the resulting values are the ascii value of that char.
这可以解决问题:
val txt = "82389235"
val numbers = txt.map { it.toString().toInt() }
map
可以进一步简化:
map(Character::getNumericValue)