Kotlin – Split string into Chunks of specific size

Split string into chunks in Kotlin

To split a given string into chunks of specific length in Kotlin, call chunked() function on the given string and pass the chunk size (an integer) as argument.

str.chunked(chunkSize)

The function returns a List of chunks.

The following is a simple use case where we take a string and display the chunk positions when chunk size is three.

a b c d e f g h i j k l m n o p
. . .|. . .|. . .|. . .|. . .|.    Chunk size = 3

Examples

Split string into chunks of chunk size = 3

In the following program, we take a string in str and split this string into chunks, where each chunk is of size three.

Kotlin Program

fun main() {
    val str = "abcdefghijklmnop"
    val chunkSize = 3
    val chunks = str.chunked(chunkSize)
    println(chunks)
}

Output

[abc, def, ghi, jkl, mno, p]