如何在""里面打印双引号?

Rah*_*ane 81 string swift

有人可以请告诉我如何以"双引号"的方式打印.

"双引号"

aya*_*aio 184

在双引号之前使用反斜杠,您希望在String中插入:

let sentence = "They said \"It's okay\", didn't they?"
Run Code Online (Sandbox Code Playgroud)

现在sentence是:

他们说"没关系",不是吗?

它被称为"转义"一个字符:你正在使用它的字面值,它不会被解释.


使用Swift 4,您也可以选择使用"""分隔符作为文本文本,而无需转义:

let sentence = """
They said "It's okay", didn't they?
Yes, "okay" is what they said.
"""
Run Code Online (Sandbox Code Playgroud)

这给出了:

他们说"没关系",不是吗?
是的,"好的"就是他们所说的.


Dan*_*iel 20

为了完整起见,请参阅Apple文档:

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

  • 转义的特殊字符\ 0(空字符),\(反斜杠),\ t(水平制表符),\n(换行符),\ r \n(回车符),\"(双引号)和\'(单引号)
  • 一个任意的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"
Run Code Online (Sandbox Code Playgroud)

myString 现在包含:

我喜欢"不必要的"引号


Ima*_*tit 6

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


1.使用转义的双引号

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

let string = "A string with \"double quotes\" in it."
print(string) //prints: A string with "double quotes" in it.
Run Code Online (Sandbox Code Playgroud)

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.
Run Code Online (Sandbox Code Playgroud)

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

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

由于多行字符串文字使用三个双引号而不是一个引号引起来,因此您可以"在多行字符串文字中包括一个双引号(),而不必对其进行转义。

let string = """
A string with "double quotes" in it.
"""
print(string) //prints: A string with "double quotes" in it.
Run Code Online (Sandbox Code Playgroud)

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.
Run Code Online (Sandbox Code Playgroud)