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将其输出到控制台,那么它可以很好地遍历字符串.

如何正确地将Char转换为Int

推荐答案

这是因为numChar,即结果值是该字符的ascii值.

这将会起到作用:

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

The map could be further simplified:

map(Character::getNumericValue)

Kotlin相关问答推荐

导入org.gradle.jvm.toolchain.internal.JavaToolchainFactory未解析引用:Java工具链工厂

可以从背景图像中点击图标吗?

collectAsState 未从存储库接收更改

按钮无法在 Android Studio 上打开新活动

区分函数和扩展

Kotlin 数据类中的大量参数

顶级属性的初始化

Kotlin 插件之间的区别

从 Kotlin 调用 Java 时可以为空的规则是什么

Kotlin JS JSON 反序列化

无法从 XML 访问 NavHostFragment

如何在调试中修复 ClassNotFoundException: kotlinx.coroutines.debug.AgentPremain?

如何解决此错误请Kotlin:[Internal Error] java.lang.ExceptionInInitializerError

Kotlin suspend fun

Kotlin:使用Gradle进行增量编译

从片段(fragment)中的点击事件启动协同程序

创建Spring和#180的实例;Kotlin中的参数化类型引用

如何在Kotlin中创建无限长的序列

在Kotlin中为Android编写库会有开销吗?

kotlin 委托有什么用?