Reputation: 378
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
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
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
Reputation: 8993
One liner:
s.lines().joinToString(transform = String::trim, separator = "\n")
Upvotes: 2