swift - 如何在 ""内打印双引号?

标签 swift string escaping

有人可以告诉我如何以“带”双引号的方式打印某些内容。

“双引号”

最佳答案

在要插入字符串的双引号之前加一个反斜杠:

let sentence = "They said \"It's okay\", didn't they?"

现在句子是:

They said "It's okay", didn't they?

这称为“转义”字符:您正在使用它的文字值,它不会被解释。

<小时/>

使用 Swift 4,您也可以选择对不需要转义的文字文本使用 """ 分隔符:

let sentence = """
They said "It's okay", didn't they?
Yes, "okay" is what they said.
"""

这给出:

They said "It's okay", didn't they?
Yes, "okay" is what they said.

<小时/>

在 Swift 5 中,您可以使用增强的分隔符:

String literals can now be expressed using enhanced delimiters. A string literal with one or more number signs (#) before the opening quote treats backslashes and double-quote characters as literal unless they’re followed by the same number of number signs. Use enhanced delimiters to avoid cluttering string literals that contain many double-quote or backslash characters with extra escapes.

您的字符串现在可以表示为:

let sentence = #"They said "It's okay", didn't they?"#

如果你想在字符串中添加变量,你还应该在反斜杠后添加#:

let sentence = #"My "homepage" is \#(url)"#

关于swift - 如何在 ""内打印双引号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37223429/

相关文章:

javascript string.replace(var1, var2)

c++ - 当测试用例数为 1 时,为什么我的程序不接受输入而是打印一个新行?

c++ - 将具有显式转义序列的字符串转换为相关字符

ios - 可达性与 NSURLSession 响应检测互联网连接

ios - 如何使用 strftime 在 Swift 中格式化字符串

objective-c - 在 Objective-C 类中导入 Swift 协议(protocol)

java - 为什么在 Eclipse 中路径需要两个斜杠 (\\)?

ios - 指向博客文章的指针不包含属于该文章的回复(Parse、Swift、iOS)

sql - 用于我的查询的 StringBuffer 或 StringBuilder

string - Haskell:如何将 "\\0"转换为 "\0"?