如何在“”中打印双引号?


Answers:


221

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

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

现在sentence是:

他们说“没关系”,不是吗?

它被称为“转义”字符:您使用的是字面值,不会被解释。


使用Swift 4,您也可以选择"""在不需要转义的文本上使用定界符:

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

这给出:

他们说“没关系”,不是吗?
是的,他们说的是“好”。


使用Swift 5,您可以使用增强的定界符:

现在可以使用增强的定界符来表示字符串文字。在开头的引号之前带有一个或多个数字符号(#)的字符串文字,除非反斜杠和双引号字符后跟相同数量的数字符号,否则将它们视为文字。使用增强的定界符可以避免使包含许多双引号或反斜杠字符以及额外转义符的字符串文字混乱。

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

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

而且,如果要将变量添加到字符串中,也应#在反斜杠后添加:

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

24

为了完整起见,来自Apple文档

字符串文字可以包含以下特殊字符:

  • 转义的特殊字符\ 0(空字符),\(反斜杠),\ t(水平制表符),\ n(换行符),\ r(回车),\“(双引号)和\'(单引号)
  • 任意Unicode标量,写为\ u {n},其中n是1–8位数的十六进制数字,其值等于有效的Unicode代码点

这意味着除了可以使用反斜杠转义字符外,还可以使用unicode值。以下两个语句是等效的:

let myString = "I love \"unnecessary\" quotation marks"
let myString = "I love \u{22}unnecessary\u{22} quotation marks"

myString 现在将包含:

我喜欢“不必要的”引号


8

根据您的需要,您可以使用以下4种模式之一来打印String其中包含双引号的Swift 。


1.使用转义的双引号

字符串文字可以包含特殊字符,例如\"

let string = "A string with \"double quotes\" in it."
print(string) //prints: A string with "double quotes" in it.

2.使用Unicode标量

字符串文字可以包含写为的Unicode标量值\u{n}

let string = "A string with \u{22}double quotes\u{22} in it."
print(string) //prints: A string with "double quotes" in it.

3.使用多行字符串文字(需要Swift 4)

雨燕编程语言/字符串和字符的状态:

因为多行字符串文字使用三个双引号而不是一个双引号,所以您可以"在多行字符串文字中包含一个双引号(),而不必对其进行转义。

let string = """
A string with "double quotes" in it.
"""
print(string) //prints: A string with "double quotes" in it.

4.使用原始字符串文字(需要Swift 5)

雨燕编程语言/字符串和字符的状态:

您可以在扩展定界符中放置字符串文字,以在字符串中包含特殊字符,而无需调用其效果。您可以将字符串放在引号(")内,并用数字符号(#)括起来。例如,打印字符串文字将#"Line 1\nLine 2"#打印换行转义序列(\n),而不是跨两行打印字符串。

let string = #"A string with "double quotes" in it."#
print(string) //prints: A string with "double quotes" in it.
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.