Search code examples
stringkotlinwhitespacetrim

Kotlin - How to trim all leading spaces from a multiline string?


String.trim() does not work for strings built using buildString. For example,

val s = buildString {
    append("{")
    append('\n')
    append(" ".repeat(5))
    append("hello")
    append(" ".repeat(7))
    append("world")
    append("}")
}
println(s.trim())

This prints

{
     hello       world}

but I need it to print

{
hello
world
}

How can I trim indent without writing my own trim method?


Solution

  • trim() only removes whitespaces from the beginning and end of a whole string, not per-line. You can remove spaces from each line with:

    s.lineSequence()
        .map { it.trim() }
        .joinToString("\n")
    

    Please note that as a side effect, above code converts all line endings to LF ("\n"). You can replace "\n" with "\r\n" or "\r" to get different results. To preserve line endings exactly as they were in the original string, we would need a more complicated solution.