본문 바로가기
코틀린/[Extraction] 추출 작업

[Kotlin][Array] sliceArray

by jinwo_o 2024. 9. 6.

지정된 인덱스 범위의 인덱스에 있는 요소를 포함하는 배열을 반환합니다.

public fun <T> Array<T>.sliceArray(indices: IntRange): Array<T> {
    if (indices.isEmpty()) return copyOfRange(0, 0)
    return copyOfRange(indices.start, indices.endInclusive + 1)
}

public actual inline fun <T> Array<T>.copyOfRange(fromIndex: Int, toIndex: Int): Array<T> {
    return if (kotlin.internal.apiVersionIsAtLeast(1, 3, 0)) {
        copyOfRangeImpl(fromIndex, toIndex)
    } else {
        if (toIndex > size) throw IndexOutOfBoundsException("toIndex: $toIndex, size: $size")
        java.util.Arrays.copyOfRange(this, fromIndex, toIndex)
    }
}


val arr = arrayOf(1, 2, 3, 4, 5)
print(arr.sliceArray(2..4).joinToString()) // 3, 4, 5

 

sliceArray - Kotlin Programming Language

 

kotlinlang.org

'코틀린 > [Extraction] 추출 작업' 카테고리의 다른 글

[Kotlin][Array] copyOfRange  (0) 2024.09.06
[Kotlin][Char] code  (0) 2024.09.03
[Kotlin][Collection] ifEmpty  (0) 2024.08.30