如何将 Char 转换为 Int? [英] How do I convert a Char to 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
?
How do I properly convert a Char
to an Int
?
推荐答案
那是因为 num
是一个 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)
这篇关于如何将 Char 转换为 Int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!