Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

lines
string
kotlin
communitycreator

How to use the lines string method in Kotlin

Programming Bytes

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 split
    var str: String = "Line 1.\nLine 2.\rLine 3.\r\nLine 4."
 
    // Using the lines() function to split the string
    var lines = str.lines()
 
    // Printing the lines
    lines.forEach { println(it) }
}
Using the lines method

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.

RELATED TAGS

lines
string
kotlin
communitycreator
RELATED COURSES

View all Courses

Keep Exploring