跳到主要内容

字符串 & 字符

字符串类型为 String ,字符类型为 Character 。

字符串是值类型,而不是引用类型。

字符串字面量

可以用一对双引号包裹字符串来表示一个字面量:

let someString = "Some string literal value"

多行字符串字面量

  • 用一对三个双引号包裹;

  • 行末会存在换行,但可以用 \ 取消换行;

  • 尾双引号会代表每行的缩进起点(第一行和最后一行不会以空白开头)。

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} 表示。其中,n 应当为 1-8 位的十六进制数。

取消转义

可以用 n 个 # 包裹字面量来取消原先转义效果:

#"Line 1\nLine 2"#    // `\n` 不会转为换行
#"Line 1\#nLine 2"# // `\#n` 会转义为换行

初始化一个空字符串

var emptyString = ""               // 字面量
emptyString.isEmpty // => true
var anotherEmptyString = String()  // 初始化语法

字符 Character

字符依然用双引号包裹:

let exclamationMark: Character = "!"

可以用 for-in 迭代 String 中的每个 Character :

for character in "Dog!🐶" {
print(character)
}

拼接字符串

可以用 + 拼接两个字符串:

let welcome = "Hello" + ", Talaxy"

可以用 += 给变量尾部拼接字符串:

var variableString = "Horse"
variableString += " and carriage"

尾部拼接字符:

let exclamationMark: Character = "!"
welcome.append(exclamationMark)

插值字符串

使用 \() 在字符串中插值:

let name = "Talaxy"

"Hello, \(name)!" // => "Hello, Talaxy!"
#"Hello, \#(name)"# // => "Hello, Talaxy!"

计算字符数量

"Hello".count   // => 5

访问 & 修改字符串

String 的下标索引类型为 String.Index ,而不是整数值类型:

let welcome = "Hello"

welcome[welcome.startIndex] // => "H"
welcome[welcome.endIndex] // => "o"
welcome[welcome.index(before: welcome.endIndex)] // => "l"
welcome[welcome.index(after: welcome.startIndex)] // => "e"
welcome[welcome.index(welcome.startIndex, offsetBy: 4)] // => "o"

// 打印 welcome 的每个字符
for index in welcome.indices {
print(welcome[index])
}

使用 insert(_:at:) or insert(contentsOf:at:) 在字符串中插入字符 or 字符串:

welcome.insert("!", at: welcome.endIndex)   // 变为 "Hello!"

welcome.insert(
contentsOf: " there~",
at: welcome.index(before: welcome.endIndex)
) // 变为 "Hello there~"

获取子字符串

String 中一些获取子字符串的方法,返回结果为 Substring 实例,而不是 String :

let greeting = "Hello, world!"
let index = greeting.firstIndex(of: ",") ?? greeting.endIndex
let beginning = greeting[..<index] // 类型为 Substring

Substring 是原字符串一段区域的引用。如果想转为 String 类型:

let newString = String(beginning)   // 类型为 String

String & Substring 都遵循 StringProtocol 协议,它们都有该协议下属性方法的实现。

字符串比较

两个字符串如果有相同的语言含义及外观(即使使用不同的 Unicode 码),则是相等的。

可以用 hasPrefix(_:) & hasSuffix(_:) 方法判断字符串是否有指定的前后缀。

Unicode

todo

Unicode 表示方法

todo

参考

Strings and Characters - docs.swift.org

String - Apple Developer Documentation