【问题标题】:Recreate Kotlin String in literal format以文字格式重新创建 Kotlin 字符串
【发布时间】:2021-03-26 12:49:48
【问题描述】:

在 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 只返回字符串,而不是在代码中重新创建它的修饰/转义。

【问题讨论】:

  • 如果您使用 Kotlin JVM,请查看 Java version of this question,由于 Kotlin-Java 互操作,您应该能够在 Kotlin JVM 中轻松使用这些解决方案

标签: string kotlin


【解决方案1】:

看起来像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 字符都将被编码为 un​​icode 转义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-29
    相关资源
    最近更新 更多