Convert a string array to an Int array in Kotlin
This article explores different ways to convert a String Array to an Int Array in Kotlin.
1. Using map() function
The standard solution is to use the map { … } with toInt() or toIntOrNull() function to convert each string in the string array to an integer. This results in a list, which can be converted to an integer array with toTypedArray() or toIntArray() function.
|
1 2 3 4 5 6 7 |
fun main() { val strings: Array<String> = arrayOf("2", "4", "6", "8"); val ints = strings.map { it.toInt() }.toTypedArray() print(ints.contentToString()) // [2, 4, 6, 8] } |
If you need an extension function, do like:
|
1 2 3 4 5 6 7 8 |
fun Array<String>.toIntArray() = this.map { it.toInt() }.toTypedArray() fun main() { val strings: Array<String> = arrayOf("2", "4", "6", "8"); val ints = strings.toIntArray() print(ints.contentToString()) // [2, 4, 6, 8] } |
2. Using forEach() function
Another approach is to use the forEach. The idea is to create an integer array and assign values to it after converting the string values to an integer.
|
1 2 3 4 5 6 7 8 |
fun main() { val strings: Array<String> = arrayOf("2", "4", "6", "8"); val ints = IntArray(strings.size) strings.indices.forEach { ints[it] = strings[it].toInt() } print(ints.contentToString()) // [2, 4, 6, 8] } |
That’s all about converting a string array to an Int array in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)