在 Kotlin 中给定一个字符串,我如何以字符串文字格式打印它?
或者以更长的形式,给定一些名为 foo 的方法来执行此操作,它将执行以下操作:
println("Howdy".foo()) --> "Howdy" (quotes included in the output)
println("1 line\n\tand a tab".foo()) --> "1 line\n\tand a tab"
println("\"embeded quotes\"".foo()) --> "\"embeded quotes\""
基本上,我正在尝试创建与字符串的代码形式相匹配的调试输出。 toString
只返回字符串,而不是在代码中重新创建它的修饰/转义。
最佳答案
好像the developers aren't particularly keen on adding the feature into the language directly ,但您始终可以自己做:
fun escapeChar(c: Char): String =
when (c) {
'\t' -> "\\t"
'\b' -> "\\b"
'\n' -> "\\n"
'\r' -> "\\r"
'"' -> "\\\""
'\\' -> "\\\\"
'\$' -> "\\\$"
in ' '..'~' -> c.toString()
else -> "\\u" + c.toInt().toString(16).padStart(4, '0')
}
fun String.escape()
= "\"${this.map(::escapeChar).joinToString("")}\""
请注意,此实现在宽容方面会出错,因此所有非 ascii 字符都将以 unicode 转义进行编码。
关于string - 以文字格式重新创建 Kotlin 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65313447/