Kotlin – Split String by Newline

Split string by Newline in Kotlin

To split a given string by newline delimiter in Kotlin, call split() function on the given string and pass the newline "\n" delimiter string as argument.

str.split("\n")

The following is a simple use case where we take a string with values separated by newline character \n. The delimiter positions are highlighted and the desired output is shown.

apple\nbanana\ncherry    <- given string
     __      __          <- delimiter positions
[apple, banana, cherry]  <- split values

Examples

Split given string by newline

In the following program, we take a string in str and split this string into values where values in the string are separated by newline "\n".

Kotlin Program

fun main() {
    val str = "apple\nbanana\ncherry"
    val values = str.split("\n")
    println(values)
}

Output

[apple, banana, cherry]