Split String to Lines

To split string to lines in Kotlin programming, you may use String.lines() function. The function lines() : splits the char sequence to a list of lines delimited by any of the following character sequences: Carriage-Return Line-Feed, Line-Feed or Carriage-Return.

Syntax – String.lines() function

The syntax of String.lines() function is

fun CharSequence.lines(): List<String> (source)

The function applied on a String returns List<String> containing lines.

ADVERTISEMENT

Example 1 – Split String to Lines

Following example demonstrates the usage of lines() function to split string to lines.

example.kt

/**
 * Kotlin example to split string to lines
 */

fun main(args: Array<String>) {
    // string to be split to lines
    var str: String = "Kotlin Tutorial.\nLearn Kotlin Programming with Ease.\rLearn Kotlin Basics."

    // splitting string using lines() function
    var lines = str.lines()

    // printing lines
    lines.forEach { println(it) }
}

Output

Kotlin Tutorial.
Learn Kotlin Programming with Ease.
Learn Kotlin Basics.

Conclusion

In this Kotlin Tutorial, we have learnt to split a string to lines using String.lines() function.