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/30167848/

相关文章:

swift - 从没有 switch/case 的枚举中获取关联值

java - 不要转义 th :content tag in Thymeleaf

swift - 如何在 Swift 中使用完成处理程序链接函数?

ios - 如何在请求后获取用户对象

swift - CocoaPods 找不到 pod "FirebaseCore": In snapshot (Podfile. 锁的兼容版本)

c - 如何从c中的字符串数组中删除一个字符串

c - 如何在任意索引处拆分字符串?

python - 如何在具有各种数据类型的列表中搜索字符串,如果它们存在则对它们执行操作?

python - 使用 SQLAlchemy 转义文件路径中的特殊字符

c - 在 C 中,\f 现在与终端中的\v 相同吗?