Get subarray of an array between given indexes in Kotlin
This article explores different ways to get a subarray of an array between given indexes in Kotlin.
1. Using copyOfRange() function
In Kotlin, you can use the copyOfRange() to copy the given range into a new array.
|
1 2 3 4 5 6 7 8 |
fun main() { val arr = intArrayOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) val start = 2 val end = 5 val subarray = arr.copyOfRange(start, end + 1) println(subarray.contentToString()) // [2, 3, 4, 5] } |
2. Using map() function
Here, the idea is to get the valid indices of the subarray in the array and transform the indices into the corresponding element in the original array and return the collection as an array.
|
1 2 3 4 5 6 7 8 9 10 11 |
fun main() { val arr = intArrayOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) val start = 2 val end = 5 val subarray = (start..end) .map { i: Int -> arr[i] } .toIntArray(); println(subarray.contentToString()) // [2, 3, 4, 5] } |
3. Custom Routine
Finally, you can write your custom routine, which creates a new array and copy elements from the original array to the new array by iterating over between given indexes.
|
1 2 3 4 5 6 7 8 9 10 11 |
fun main() { val arr = intArrayOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) val start = 2 val end = 5 val subarray = IntArray(end - start + 1) for (i in subarray.indices) { subarray[i] = arr[start + i] } println(subarray.contentToString()) // [2, 3, 4, 5] } |
That’s all about getting a subarray of an array between given indexes 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 :)