文章目录
字符串是诸如 “hello, world”,“abcdefg” 这样有序的字符(Character)类型的值的集合,通过 String 类型来表示。
注意:
Swift 的 String 类型与 Foundation NSString 类进行了无缝桥接。Foundation 还对 String 进行扩展使其可以访问 NSString 类型中定义的方法。这意味着调用那些 NSString 的方法,你无需进行任何类型转换。
字符串字面量
字符串字面量可以用于为常量和变量提供初始值。
let something = "Some string literal value"
多行字符串字面量
多行字符串字面量由一对三个双引号包裹着的具有固定顺序的文本字符集。
let quotation = """
The White Rabbit put on his spectacles. "Where shall I begin,
please your Majesty?" he asked.
"Begin at the beginning," the King said gravely, "and go on
till you come to the end; then stop."
"""
print(quotation)
如果代码中,多行字符串字面量包含换行符的话,则多行字符串字面量中也会包含换行符。如果代码中为了增加可读性包含了换行符,但又不想在多行字符串字面量中出现换行符的话,可以在行尾写一个反斜杠(\)作为续行符。
let softWrappedQuotation = """
The White Rabbit put on his spectacles. "Where shall I begin, \
please your Majesty?" he asked.
"Begin at the beginning," the King said gravely, "and go on \
till you come to the end; then stop."
"""
字符串字面量的特殊字符
字符串字面量可以包含以下特殊字符:
转义字符:\0(空字符)、\(反斜杠)、\t(水平制表符)、\n(换行符)、\r(回车符)、"(双引号)、’(单引号);
Unicode标量,写成\u{n}(u为小写),其中n为任意一到八位十六进制数且可用的Unicode位码。
下面的代码为各种特殊字符的使用示例。wiseWords 常量包含了两个双引号,dollarSign、blackHeart 和 sparklingHeart 常量演示了三种不同格式的 Unicode 标量:
let wiseWords = "\"Imagination is more important than knowledge\" - Einstein"
// "Imageination is more important than knowledge" - Enistein
let dollarSign = "\u{24}" // $,Unicode 标量 U+0024
let blackHeart = "\u{2665}" // ♥,Unicode 标量 U+2665
let sparklingHeart = "\u{1F496}" // ?,Unicode 标量 U+1F496
由于多行字符串字面量使用了三个双引号,而不是一个,所以你可以在多行字符串字面量里直接使用双引号(")而不必加上转义符(\)。要在多行字符串字面量中使用 “”" 的话,就需要使用至少一个转义符(\):
let threeDoubleQuotes = """
Escaping the first quote \"""
Escaping all three quotes \"\"\"
"""
扩展字符串分隔符
你可以将字符串文字放在扩展分隔符中,这样字符串中的特殊字符将会被直接包含而非转义后的效果。
将字符串放在引号(")中并用数字符号(#)括起来。
例如,打印字符串文字 #“Line 1 nLine 2”# 打印换行符转义序列(\n)而不是进行换行打印。
如果需要字符串文字中字符的特殊效果,请匹配转义字符(\)后面添加与起始位置个数相匹配的 # 符。
例如,如果你的字符串是 #“Line 1 nLine 2”# 并且您想要换行,则可以使用 #“Line 1 #nLine 2”# 来代替。
同样,