Split a String into chunks of given size in Kotlin
This article explores different ways to split a String into chunks of the given size in Kotlin.
1. Using chunked() function
The standard solution to split a String into a list of strings is using the chunked() function, where each string does not exceed the specified size. The following code example shows invocation for this method:
|
1 2 3 4 5 6 7 8 |
fun main() { val s = "ABCDEFGHIJKLMNO" val size = 5 val chunks = s.chunked(size) println(chunks) // [ABCDE, FGHIJ, KLMNO] } |
2. Using substring() function
Another option to partition a string into fixed-length chunks is using the substring() function. This would translate to a simple code below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
fun split(s: String, size: Int): List<String> { val chunks = mutableListOf<String>() var i = 0 while (i < s.length) { chunks.add(s.substring(i, Math.min(s.length, i + size))) i += size } return chunks } fun main() { val s = "ABCDEFGHIJKLMNO" val size = 5 println(split(s, size)) // [ABCDE, FGHIJ, KLMNO] } |
3. Using Regex
Finally, we can split a string into equal size chinks around matches of the given regular expression. The following solution demonstrates this by creating a matcher and generate the start and the end index of each chunk.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import java.util.regex.Pattern fun main() { val s = "ABCDEFGHIJKLMNO" val size = 5 val match = Pattern.compile(".{1,$size}").matcher(s) val chunks = mutableListOf<String>() while (match.find()) { chunks.add(s.substring(match.start(), match.end())) } println(chunks) // [ABCDE, FGHIJ, KLMNO] } |
That’s all about splitting a String into chunks of the given size 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 :)