如何在Swift中打印转义序列字符?

Wil*_*ill 3 swift

抱歉,标题不清楚。

我的意思是:如果我有一个变量,我们将其称为a,其值为“ Hello \ nWorld”,它将写为

var a = "Hello\nWorld
Run Code Online (Sandbox Code Playgroud)

如果我要打印它,我会得到

Hello
World 
Run Code Online (Sandbox Code Playgroud)

我如何将其打印为:

Hello\nWorld
Run Code Online (Sandbox Code Playgroud)

Jor*_*dan 8

我知道这有点旧,但是我一直在寻找解决同一问题的方法,并且找到了一些简单的方法。

如果你想打印一个显示转义字符的字符串,比如“\nThis Thing\nAlso this”

打印(myString.debugDescription)


Ale*_*ica 5

这是@Pedro Castilho的答案的更完整版本。

import Foundation

extension String {
    static let escapeSequences = [
        (original: "\0", escaped: "\\0"),
        (original: "\\", escaped: "\\\\"),
        (original: "\t", escaped: "\\t"),
        (original: "\n", escaped: "\\n"),
        (original: "\r", escaped: "\\r"),
        (original: "\"", escaped: "\\\""),
        (original: "\'", escaped: "\\'"),
    ]

    mutating func literalize() {
        self = self.literalized()
    }

    func literalized() -> String {
        return String.escapeSequences.reduce(self) { string, seq in
            string.replacingOccurrences(of: seq.original, with: seq.escaped)
        }
    }
}

let a = "Hello\0\\\t\n\r\"\'World"
print("Original: \(a)\r\n\r\n\r\n")
print("Literalized: \(a.literalized())")
Run Code Online (Sandbox Code Playgroud)


Ped*_*lho 2

你不能,除非改变字符串本身。这\n序列仅作为换行符的表示存在于代码中,编译器会将其更改为实际的换行符。

换句话说,这里的问题是“原始”字符串是带有实际换行符的字符串。

如果您希望它显示为实际的\n,则需要转义反斜杠。(改为\\n

您还可以使用以下函数来自动执行此操作:

func literalize(_ string: String) -> String {
    return string.replacingOccurrences(of: "\n", with: "\\n")
                 .replacingOccurrences(of: "\t", with: "\\t")
}
Run Code Online (Sandbox Code Playgroud)

等等。您可以replacingOccurrences为每个要字面化的转义序列添加更多调用。