In this tutorial, you shall learn how to split a given string into list of lines in Kotlin, using String.lines() function, with examples.

Kotlin – Split String into List of Lines

To split a given string into list of lines which are delimited by a new line, line feed, or carriage return, call lines() method on this String.

Example

In the following example, we take a string in str, which contains lines delimited by new line character. We split this string into list of lines using lines() method.

Main.kt

</>
Copy
fun main(args: Array<String>) {
    var str = "hello world.\ngood morning.\nrun."
    var lines = str.lines()
    for (line in lines) {
        println(line)
    }
}

Output

hello world.
good morning.
run.

Conclusion

In this Kotlin Tutorial, we learned how to split a given String into List of lines, using String.lines() method, with the help of Kotlin example programs.