To split an array in Kotlin, you can use the sliceArray
method to create subarrays from the original array.
In this example,
arr
with integer values.sliceArray
method to create a subarray containing the first three elements of arr
. This is done by passing a range (0..2) to the sliceArray
method.sliceArray
method again to create another subarray containing the remaining elements of arr
. This is done by passing a range (3 until arr.size) to the sliceArray
method.fun main(args: Array<String>) {
val arr = arrayOf(1, 2, 3, 4, 5, 6)
val firstHalf = arr.sliceArray(0..2)
val secondHalf = arr.sliceArray(3 until arr.size)
println("First half: ${firstHalf.joinToString()}")
println("Second half: ${secondHalf.joinToString()}")
}
First half: 1, 2, 3 Second half: 4, 5, 6
In this example,
arr
with string values.sliceArray
method to create a subarray containing the first two elements of arr
. This is done by passing a range (0..1) to the sliceArray
method.sliceArray
method again to create another subarray containing the remaining elements of arr
. This is done by passing a range (2 until arr.size) to the sliceArray
method.fun main(args: Array<String>) {
val arr = arrayOf("apple", "banana", "cherry", "date")
val firstHalf = arr.sliceArray(0..1)
val secondHalf = arr.sliceArray(2 until arr.size)
println("First half: ${firstHalf.joinToString()}")
println("Second half: ${secondHalf.joinToString()}")
}
First half: apple, banana Second half: cherry, date
In this tutorial, we learned How to Split an Array in Kotlin language with well detailed examples.