To get a subarray from a given array in Kotlin, you can use the sliceArray()
method or the array slicing syntax.
In this example,
numbers
with some elements.sliceArray()
method and store the result in the variable subArray
.fun main() {
val numbers = intArrayOf(1, 2, 3, 4, 5);
val subArray = numbers.sliceArray(1..3);
println("Subarray: ${subArray.contentToString()}");
}
Subarray: [2, 3, 4]
In this example,
words
with some elements.sliceArray()
method and store the result in the variable subArray
.fun main() {
val words = arrayOf("apple", "banana", "cherry", "date", "elderberry");
val subArray = words.sliceArray(1..3);
println("Subarray: ${subArray.contentToString()}");
}
Subarray: [banana, cherry, date]
In this tutorial, we learned How to get Sub Array in Kotlin language with well detailed examples.