How to split a string by newline in Kotlin

1 Answer

0 votes
/**
 * Splits a multi-line string into a list of individual lines.
 * Automatically handles cross-platform line endings (Unix LF and Windows CRLF)
 * and strips trailing newline characters.
 *
 * @param text The input string to split (nullable for safety).
 * @return A List<String> containing each individual line.
 */
fun splitByNewline(text: String?): List<String> {
    // Guard clause: return an empty list if the input is null or empty
    if (text.isNullOrEmpty()) {
        return emptyList()
    }
    
    // lines() natively handles both \n and \r\n, returning List<String>
    return text.lines()
}

fun main() {
    // Sample text containing mixed line endings (Unix LF, Windows CRLF, and an empty line)
    val multilineText = "Hello world!\nThis is line two.\r\n\nFinal line here."

    // Call the splitting function
    val resultLines = splitByNewline(multilineText)

    // Print out the parsed lines with their indices
    resultLines.forEachIndexed { index, line ->
        println("Line ${index + 1}: '$line'")
    }
}


/*
run:

Line 1: 'Hello world!'
Line 2: 'This is line two.'
Line 3: ''
Line 4: 'Final line here.'

*/

 



answered 10 hours ago by avibootz
...