Legend123
Legend123

Reputation: 378

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?

Upvotes: 2

Views: 5415

Answers (3)

Adam Millerchip
Adam Millerchip

Reputation: 23091

You could use a regular expression to trim leading whitespace:

val s = buildString {
    append("{")
    append('\n')
    append(" ".repeat(5))
    append("hello\n")
    append(" ".repeat(7))
    append("world\n")
    append("}")
}
println(s.replace(Regex("""^\s+""", RegexOption.MULTILINE), ""))

Output:

{
hello
world
}

Upvotes: 1

broot
broot

Reputation: 28352

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.

Upvotes: 7

Sebi
Sebi

Reputation: 8993

One liner:

s.lines().joinToString(transform = String::trim, separator = "\n")

Upvotes: 2

Related Questions