【发布时间】:2021-08-14 02:52:15
【问题描述】:
String.trim() 不适用于使用buildString 构建的字符串。例如,
val s = buildString {
append("{")
append('\n')
append(" ".repeat(5))
append("hello")
append(" ".repeat(7))
append("world")
append("}")
}
println(s.trim())
打印出来
{
hello world}
但我需要它来打印
{
hello
world
}
如何在不编写自己的修剪方法的情况下修剪缩进?
【问题讨论】:
-
您可能想使用
trimIndent(),而不是trim()。 -
trim()仅删除字符串开头和结尾的空格。它不会删除字符串中的空格。 -
@broot
trimIndent()不会删除一行中的所有前导空格 -
您的示例代码仅包含一个换行符。对吗?
标签: string kotlin whitespace trim