以文字格式重新创建 Kotlin 字符串

Tra*_*ggs 3 string kotlin

给定 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\""
Run Code Online (Sandbox Code Playgroud)

基本上我正在尝试创建与字符串的代码形式匹配的调试输出。toString仅返回字符串,而不是在代码中重新创建它的修饰/转义。

Apl*_*123 5

开发人员似乎并不特别热衷于直接将该功能添加到语言中,但您始终可以自己完成:

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("")}\""
Run Code Online (Sandbox Code Playgroud)

请注意,此实现在宽大方面犯了错误,因此所有非 ascii 字符都将被编码为 un​​icode 转义。