Get a subarray of an array between given positions in Kotlin
This article explores different ways to get a subarray of an array between the specified range in Kotlin.
1. Using copyOfRange() function
The standard way to get a subarray of an array in Kotlin is to use the extension function copyOfRange(), which returns a new array, a copy of the specified range of the original array.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
fun <T> getSubArray(array: Array<T>, beg: Int, end: Int): Array<T> { return array.copyOfRange(beg, end + 1) } fun main() { val arr = arrayOf('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H') val beg = 1 val end = 4 val subarray = getSubArray(arr, beg, end) println(subarray.contentToString()) // [B, C, D, E] } |
2. Using System.arraycopy() function
The System.arraycopy() function can also be used to get a copy from the specified range in the source array to the destination array.
|
1 2 3 4 5 6 7 8 9 10 |
fun main() { val arr = arrayOf('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H') val start = 1 val end = 4 val subarray = arrayOfNulls<Char>(end - start + 1) System.arraycopy(arr, start, subarray, 0, subarray.size) println(subarray.contentToString()) // [B, C, D, E] } |
3. Using subList() with toTypedArray() function
Another plausible way of getting a subarray from an array in the specific range involves using a List. The idea is to convert the array into a list and then use the subList() function to get elements in the specified range. We can then call the toTypedArray() function to convert elements into a new array.
|
1 2 3 4 5 6 7 8 9 10 11 |
fun main() { val arr = arrayOf('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H') val start = 1 val end = 4 val subarray = arr.toList() .subList(start, end + 1) .toTypedArray() println(subarray.contentToString()) // [B, C, D, E] } |
4. Using map() with toTypedArray() function
We can also use the map() function to get a list of elements in the specified range, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 |
fun main() { val arr = arrayOf('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H') val start = 1 val end = 4 val subarray = (start..end) .map { i: Int -> arr[i] } .toTypedArray() println(subarray.contentToString()) // [B, C, D, E] } |
5. Custom Routine
We can also write our own custom function to copy elements in the specified range from the source array into the new array.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
fun main() { val arr = arrayOf('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H') val start = 1 val end = 4 val subarray: Array<Char?> = arrayOfNulls(end - start + 1) for (i in subarray.indices) { subarray[i] = arr[start + i] } println(subarray.contentToString()) // [B, C, D, E] } |
That’s all about getting a subarray of an array between given positions 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 :)