如何在 Kotlin 中将 String 数组转换为 Int 数组? [英] How to convert String array to Int array in Kotlin?

查看:53
本文介绍了如何在 Kotlin 中将 String 数组转换为 Int 数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Kotlin 有许多简写和有趣的功能.所以,我想知道是否有一些快速而简短的方法可以将字符串数组转换为整数数组.类似于 Python 中的这段代码:

Kotlin has many shorthands and interesting features. So, I wonder if there is some fast and short way of converting array of string to array of integers. Similar to this code in Python:

results = [int(i) for i in results]

推荐答案

你可以使用 .map { ... }.toInt().toIntOrNull():

You can use .map { ... } with .toInt() or .toIntOrNull():

val result = strings.map { it.toInt() }

只有结果不是数组而是列表.最好在非性能关键代码中对数组使用列表,请参阅 差异.

Only the result is not an array but a list. It is preferable to use lists over arrays in non-performance-critical code, see the differences.

如果需要数组,添加 .toTypedArray().toIntArray().

If you need an array, add .toTypedArray() or .toIntArray().

这篇关于如何在 Kotlin 中将 String 数组转换为 Int 数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆