Split String to Lines in Kotlin using String.lines()
To split a string to lines in Kotlin, use the String.lines() function. It reads the text as a sequence of lines and returns a List<String>. This is the simplest option when your input may contain different newline formats, such as Unix line feed, Windows carriage-return line-feed, or old-style carriage return.
The lines() function is useful when you are processing multi-line text from a file, textarea, log message, copied text, or API response.
Line separators handled by Kotlin String.lines()
Kotlin String.lines() splits the character sequence around common line separators. It handles these newline sequences:
\n– line feed, commonly used on Unix, Linux, and modern macOS systems\r\n– carriage return followed by line feed, commonly used on Windows\r– carriage return, used by some older text formats
Because of this, lines() is usually safer than manually splitting only by "\n" when the source text may come from different operating systems.
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.
Since lines() is an extension on CharSequence, it can be called directly on a Kotlin String.
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.
Kotlin lines() example with Windows and Unix newline characters
The next example uses both \r\n and \n in the same string. Kotlin still returns each logical line as a separate item in the list.
fun main() {
val text = "First line\r\nSecond line\nThird line"
val result = text.lines()
println(result)
println("Number of lines: ${result.size}")
}
Output
[First line, Second line, Third line]
Number of lines: 3
Blank lines and trailing newline behavior in Kotlin lines()
If the string contains blank lines, lines() keeps them as empty strings in the returned list. If the string ends with a newline, the returned list contains a final empty string.
fun main() {
val text = "Apple\n\nBanana\n"
val lines = text.lines()
lines.forEachIndexed { index, line ->
println("$index: '$line'")
}
}
Output
0: 'Apple'
1: ''
2: 'Banana'
3: ''
If you do not want empty lines in the final list, filter them after calling lines().
fun main() {
val text = "Apple\n\nBanana\n"
val nonEmptyLines = text.lines().filter { it.isNotEmpty() }
println(nonEmptyLines)
}
Output
[Apple, Banana]
Trim spaces from each line after splitting a Kotlin string
lines() only splits the string. It does not remove spaces before or after the text in each line. If each line may contain extra whitespace, call trim() on every line.
fun main() {
val text = " Kotlin \n Java \n Python "
val trimmedLines = text.lines().map { it.trim() }
println(trimmedLines)
}
Output
[Kotlin, Java, Python]
Kotlin lines() vs split(“\\n”) for line-based text
For simple strings that always use \n, split("\n") can work. But for line-based text, lines() is usually clearer and more complete because it recognizes \n, \r\n, and \r.
| Requirement | Recommended Kotlin function | Reason |
|---|---|---|
| Split text into lines | lines() | Handles common newline formats directly |
| Split text by comma, space, pipe, or another delimiter | split() | Useful for custom separators |
| Remove empty lines after splitting | lines().filter { it.isNotEmpty() } | Keeps the line-splitting behavior and then filters the result |
| Trim each line after splitting | lines().map { it.trim() } | Splits first and then cleans each line |
Use split() when you are splitting by a custom separator such as a comma, tab, colon, or pipe symbol. Use lines() when the separator is a line break.
Read a multi-line string and loop through each line in Kotlin
After calling lines(), you can use normal collection operations such as forEach, map, filter, and forEachIndexed.
fun main() {
val message = "Name: Alex\nCity: Chennai\nRole: Developer"
message.lines().forEach { line ->
println("Line value = $line")
}
}
Output
Line value = Name: Alex
Line value = City: Chennai
Line value = Role: Developer
Official Kotlin references for String.lines() and split()
For the standard library definitions, refer to the Kotlin documentation for CharSequence.lines() and CharSequence.split(). These functions are part of Kotlin’s text-processing utilities.
Frequently asked questions about splitting Kotlin strings into lines
How to split a string by lines in Kotlin?
Use string.lines(). It returns a List<String>, where each item is one line from the original string.
Does Kotlin lines() handle Windows line breaks?
Yes. Kotlin lines() handles \r\n, \n, and \r line separators.
What is the difference between lines() and split() in Kotlin?
lines() is designed for splitting text by line separators. split() is a more general function used for custom delimiters such as commas, spaces, tabs, or symbols.
Does Kotlin lines() remove blank lines?
No. Blank lines are returned as empty strings. To remove them, use string.lines().filter { it.isNotEmpty() }.
How to trim every line after using String.lines()?
Use string.lines().map { it.trim() }. This keeps the line splitting separate from whitespace cleanup.
QA checklist for Kotlin String.lines() examples
- Verify that examples show at least one newline separator such as
\n,\r\n, or\r. - Check that the returned value is explained as
List<String>. - Confirm that blank-line behavior is not described as automatic removal.
- Use
lines()for line breaks andsplit()only when discussing custom delimiters. - Keep Kotlin code examples small enough to run directly in a
main()function.
Conclusion
In this Kotlin Tutorial, we have learnt to split a string to lines using String.lines() function. Use lines() when you want to process line-based text, and use split() when you need to split by a custom delimiter.
TutorialKart.com