The lines
method in Kotlin splits a single string into a list of multiple lines based on the following characters:
\n
\r
fun CharSequence.lines(): List<String>
This method doesn’t take any arguments.
This method returns a List
of String
as a return value.
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) }}
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.