字符串
是一系列字符的集合,例如 "hello, world"
,"albatross"
。Swift 的字符串通过 String
类型来表示
1、字符串字面量
字符串字面量是由一对双引号包裹着的具有固定顺序的字符集。可以用于为常量和变量提供初始值。
let someString = "Some string literal value"
(1)多行字符串字面量
多行字符串字面量是由一对三个双引号("""
)包裹的具有固定顺序的文本字符集
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."
"""
(2)字符串字面量的特殊字符
字符串字面量可以包含以下特殊字符:
- 转义字符
\0
(空字符)、\\
(反斜线)、\t
(水平制表符)、\n
(换行符)、\r
(回车符)、\"
(双引号)、\'
(单引号)。 - Unicode 标量,写成
\u{n}
(u 为小写),其中n
为任意一到八位十六进制数且可用的 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
2、初始化字符串
- 要创建一个空字符串作为初始值,可以将空的字符串字面量赋值给变量,也可以初始化一个新的
String
var emptyString = "" // 空字符串字面量
var anotherEmptyString = String() // 初始化方法
// 两个字符串均为空并等价。
- 可以通过检查
Bool
类型的isEmpty
属性来判断该字符串是否为空
if emptyString.isEmpty {
print("Nothing to see here")
}
// 打印输出:“Nothing to see here”
3、字符串可变性
通过将一个特定字符串分配给一个变量来对其进行修改,或者分配给一个常量来保证其不会被修改:
var variableString = "Horse"
variableString += " and carriage"
// variableString 现在为 "Horse and carriage"
let constantString = "Highlander"
constantString += " and another Highlander"
// 这会报告一个编译错误(compile-time error) - 常量字符串不可以被修改。
4、字符串是值类型
5、使用字符
- 通过
for-in
循环来遍历字符串,获取字符串中每一个字符的值
for character in "Dog!🐶" {
print(character)
}
// D
// o
// g
// !
// 🐶
- 通过标明一个
Character
类型并用字符字面量进行赋值,可以建立一个独立的字符常量或变量:
let exclamationMark: Character = "!"
- 字符串可以通过传递一个值类型为
Character
的数组作为自变量来初始化:
let catCharacters: [Character] = ["C", "a", "t", "!", "🐱"]
let catString = String(catCharacters)
print(catString)
// 打印输出:“Cat!🐱”
6、连接字符串和字符
- 字符串可以通过加法运算符(
+
)相加在一起(或称“连接”)创建一个新的字符串
let string1 = "hello"
let string2 = " there"
var welcome = string1 + string2
// welcome 现在等于 "hello there"
- 可以通过加法赋值运算符(
+=
)将一个字符串添加到一个已经存在字符串变量上
var instruction = "look over"
instruction += string2
// instruction 现在等于 "look over there"
- 可以用
append()
方法将一个字符附加到一个字符串变量的尾部:
let exclamationMark: Character = "!"
welcome.append(exclamationMark)
// welcome 现在等于 "hello there!"
注意:不能将一个字符串或者字符添加到一个已经存在的字符变量上,因为字符变量只能包含一个字符。
7、字符串插值
字符串插值是一种构建新字符串的方式,可以在其中包含常量
、变量
、字面量
和表达式
。字符串字面量
和多行字符串字面量
都可以使用字符串插值。
let multiplier = 3
let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)"
// message 是 "3 times 2.5 is 7.5"
8、计算字符数量
可以使用 count
属性来获得一个字符串中 Character
值的数量。
let unusualMenagerie = "Koala 🐨, Snail 🐌, Penguin 🐧, Dromedary 🐪"
print("unusualMenagerie has \(unusualMenagerie.count) characters")
// 打印输出“unusualMenagerie has 40 characters”
9、访问和修改字符串
(1)字符串索引
每一个 String
值都有一个关联的索引(index)类型,String.Index
,它对应着字符串中的每一个 Character
的位置。
- 使用
startIndex
属性可以获取一个String
的第一个Character
的索引 - 使用
endIndex
属性可以获取最后一个Character
的后一个位置的索引 - 如果
String
是空串,startIndex
和endIndex
是相等的 - 调用
String
的index(before:)
或index(after:)
方法,可以立即得到前面或后面的一个索引 - 调用
index(_:offsetBy:)
方法来获取对应偏移量的索引
let greeting = "Guten Tag!"
greeting[greeting.startIndex]
// G
greeting[greeting.index(before: greeting.endIndex)]
// !
greeting[greeting.index(after: greeting.startIndex)]
// u
let index = greeting.index(greeting.startIndex, offsetBy: 7)
greeting[index]
// a
- 使用
indices
属性会创建一个包含全部索引的范围(Range
),用来在一个字符串中访问单个字符
for index in greeting.indices {
print("\(greeting[index]) ", terminator: "")
}
// 打印输出“G u t e n T a g ! ”
(2)插入和删除
- 调用
insert(_:at:)
方法可以在一个字符串的指定索引插入一个字符 - 调用
insert(contentsOf:at:)
方法可以在一个字符串的指定索引插入一个段字符串
var welcome = "hello"
welcome.insert("!", at: welcome.endIndex)
// welcome 变量现在等于 "hello!"
welcome.insert(contentsOf:" there", at: welcome.index(before: welcome.endIndex))
// welcome 变量现在等于 "hello there!"
- 调用
remove(at:)
方法可以在一个字符串的指定索引删除一个字符 - 调用
removeSubrange(_:)
方法可以在一个字符串的指定索引删除一个子字符串
welcome.remove(at: welcome.index(before: welcome.endIndex))
// welcome 现在等于 "hello there"
let range = welcome.index(welcome.endIndex, offsetBy: -6)..<welcome.endIndex
welcome.removeSubrange(range)
// welcome 现在等于 "hello"
10、子字符串
- 使用下标或者
prefix(_:)
之类的方法 —— 就可以得到一个SubString
的实例,而非另外一个String
- Swift 里的
SubString
绝大部分函数都跟String
一样,意味着可以使用同样的方式去操作SubString
和String
-
SubString
重用了原String
的内存空间,不适合长期存储,在短时间内需要操作字符串时,才会使用SubString
。当需要长时间保存结果时,就把SubString
转化为String
的实例
let greeting = "Hello, world!"
let index = greeting.firstIndex(of: ",") ?? greeting.endIndex
let beginning = greeting[..<index]
// beginning 的值为 "Hello"
// 把结果转化为 String 以便长期存储。
let newString = String(beginning)
11、比较字符串
(1)字符串/字符相等
字符串/字符可以用等于操作符(==
)和不等于操作符(!=
)
let quotation = "We're a lot alike, you and I."
let sameQuotation = "We're a lot alike, you and I."
if quotation == sameQuotation {
print("These two strings are considered equal")
}
// 打印输出“These two strings are considered equal”
(2)前缀/后缀相等
通过调用字符串的 hasPrefix(_:)
/hasSuffix(_:)
方法来检查字符串是否拥有特定前缀/后缀,两个方法均接收一个 String
类型的参数,并返回一个布尔值。
let romeoAndJuliet = [
"Act 1 Scene 1: Verona, A public place",
"Act 1 Scene 2: Capulet's mansion",
"Act 1 Scene 3: A room in Capulet's mansion",
"Act 1 Scene 4: A street outside Capulet's mansion",
"Act 1 Scene 5: The Great Hall in Capulet's mansion",
"Act 2 Scene 1: Outside Capulet's mansion",
"Act 2 Scene 2: Capulet's orchard",
"Act 2 Scene 3: Outside Friar Lawrence's cell",
"Act 2 Scene 4: A street in Verona",
"Act 2 Scene 5: Capulet's mansion",
"Act 2 Scene 6: Friar Lawrence's cell"
]
var act1SceneCount = 0
for scene in romeoAndJuliet {
if scene.hasPrefix("Act 1 ") {
act1SceneCount += 1
}
}
print("There are \(act1SceneCount) scenes in Act 1")
// 打印输出“There are 5 scenes in Act 1”
var mansionCount = 0
var cellCount = 0
for scene in romeoAndJuliet {
if scene.hasSuffix("Capulet's mansion") {
mansionCount += 1
} else if scene.hasSuffix("Friar Lawrence's cell") {
cellCount += 1
}
}
print("\(mansionCount) mansion scenes; \(cellCount) cell scenes")
// 打印输出“6 mansion scenes; 2 cell scenes”
网友评论