How to use the lines string method in Kotlin
Overview
The lines method in Kotlin splits a single string into a list of multiple lines based on the following characters:
- Line feed:
\n - Carriage return:
\r
Syntax
fun CharSequence.lines(): List<String>
Arguments
This method doesn’t take any arguments.
Return value
This method returns a List of String as a return value.
Code example
The code below demonstrates how to use the lines method in Kotlin:
fun main() {// The string to be splitvar str: String = "Line 1.\nLine 2.\rLine 3.\r\nLine 4."// Using the lines() function to split the stringvar lines = str.lines()// Printing the lineslines.forEach { println(it) }}
Explanation
Line 3: We create a string with line feed (\n) and carriage return (\r) characters.
Line 6: We use the lines method to split the string into multiple strings delimited by the new line characters.
Line 9: We use the forEach method to print the list of strings returned by the lines method.