1. 字符串字面量
let someString = "Some string literal value"
// someString 常量被推斷類型為 String
2. 空字符串的初始化
兩種方式,舉個(gè)栗子?? :
var emptyString = "" // 方式一
var anotherEmptyString = String() // 方式二
// 兩種方式都初始化為一個(gè)空字符串断盛,即 “”弯予。
通過(guò)檢查字符串常量或變量的isEmpty
屬性來(lái)確認(rèn)一個(gè)String
值是否為空:
if emptyString.isEmpty {
print("Nothing to see here")
}
// 結(jié)果為: "Nothing to see here"
3. 字符串可變性
String
常量不可修改值;
String
變量 可以修改值刊棕。
4. 字符串是值類型
值類型意味著炭晒,每一次賦值,拿到的都是String
對(duì)象的拷貝甥角,而非對(duì)象本身网严。 (淺拷貝)
5. 字符類型 (Character)
- 用字符串字面量初始化一個(gè)Character類型的變量:
let exclamationMark: Character = "!"
- 用
for...in
語(yǔ)句遍歷String類型對(duì)象,打印所有字符嗤无,舉個(gè)?? :
for character in "Dog!?".characters {
print(character)
}
// D
// o
// g
// !
// ?
- 用字符數(shù)組初始化一個(gè)字符串:
let catCharacters: [Character] = ["C", "a", "t", "!", "??"] // 初始化一個(gè)字符數(shù)組
let catString = String(catCharacters) // 將數(shù)組轉(zhuǎn)化為字符串
print(catString) // 結(jié)果為: "Cat!??"
6. 連接字符串或字符
舉個(gè)?? :
let string1 = "hello"
let string2 = " there"
var welcome = string1 + string2
// welcome 現(xiàn)在為 "hello there"
上面的?? 也可以簡(jiǎn)寫為下面的 ?? :
var instruction = "look over"
instruction += string2
// instruction 現(xiàn)在為 "look over there"
字符串后追加字符, 使用append(_)
函數(shù):
let exclamationMark: Character = "!"
welcome.append(exclamationMark)
// welcome 現(xiàn)在為 "hello there!"
7. 字符串插值
一個(gè)反斜杠 \ 加上一枚小括號(hào)()
等于 \()
, 舉個(gè)?? :
let multiplier = 3
let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)"
// message 為 "3 times 2.5 is 7.5"
8. 字符串的字符統(tǒng)計(jì)
let unusualMenagerie = "Koala ??, Snail ??, Penguin ??, Dromedary ?? "
print("unusualMenagerie has \(unusualMenagerie.characters.count) characters")
// 'unusualMenagerie.characters' 為字符串的字符數(shù)組震束,然后取其count值,即此字符串的字符數(shù)量当犯。
// 結(jié)果為: "unusualMenagerie has 40 characters"
9. 訪問(wèn)和修改字符串
字符串索引
每一個(gè)String
值都有索引類型垢村,String.Index
,它相當(dāng)于每個(gè)Character
在字符串中的位置嚎卫。使用startIndex
屬性來(lái)訪問(wèn)String
中第一個(gè)Character
的位置:
let greeting = "Guten Tag!"
greeting[greeting.startIndex] // G
endIndex
屬性是 String
中最后一個(gè)字符再往后一位的位置肝断。因此,endIndex
屬性并不是字符串下標(biāo)腳本的合法實(shí)際參數(shù)。如果String
為空胸懈,則 startIndex
與 endIndex
相等担扑。
使用 index(before:)
和 index(after:)
方法來(lái)訪問(wèn)給定索引的前或后一個(gè)位置:
greeting[greeting.index(before: greeting.endIndex)]
// !
greeting[greeting.index(after: greeting.startIndex)]
// u
使用index(_:offsetBy:)
方法訪問(wèn)偏離第一個(gè)參數(shù)某個(gè)長(zhǎng)度的位置:
let index = greeting.index(greeting.startIndex, offsetBy: 7)
greeting[index]
// a
嘗試訪問(wèn)索引位置在字符串范圍之外,就會(huì)觸發(fā)運(yùn)行時(shí)錯(cuò)誤:
greeting[greeting.endIndex] // error
greeting.index(after: endIndex) // error
字符串characters
屬性是一個(gè)字符數(shù)組趣钱,數(shù)組的indices
(index
的復(fù)數(shù)形式)屬性涌献,代表字符串的索引數(shù)組:
for index in greeting.characters.indices {
print("\(greeting[index]) ", terminator: " ")
}
// 結(jié)果為: "G u t e n T a g ! "
插入和刪除
插入字符,使用insert(_:at:)
方法首有,
插入字符串燕垃,使用insert(contentsOf:at:)
方法:
var welcome = "hello"
welcome.insert("!", at: welcome.endIndex)
// welcome 現(xiàn)在為 "hello!"
welcome.insert(contentsOf:" there".characters, at: welcome.index(before: welcome.endIndex))
// welcome 現(xiàn)在為 "hello there!"
移除某個(gè)位置字符,使用remove(at:)
方法井联,
移除某段位置字符卜壕,使用removeSubrange(_:)
方法:
welcome.remove(at: welcome.index(before: welcome.endIndex))
// welcome 現(xiàn)在為 "hello there"
let range = welcome.index(welcome.endIndex, offsetBy: -6)..<welcome.endIndex
welcome.removeSubrange(range)
// welcome 現(xiàn)在為 "hello"
任何遵循RangeReplaceableIndexable協(xié)議的類型都可使用
insert(_:at:)
,insert(contentsOf:at:)
烙常,remove(at:)
方法轴捎,包括 String類型,還有集合類型如 :Array
蚕脏,Dictionary
和Set
侦副。
10. 字符串比較
字符串和字符相等性
字符串比較使用“等于”運(yùn)算符 (==
) 和“不等”運(yùn)算符 (!=
)進(jìn)行檢查:
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")
}
// 結(jié)果為: "These two strings are considered equal"
前綴和后綴相等性
要檢查一個(gè)字符串是否擁有特定的字符串前綴或者后綴,調(diào)用字符串的hasPrefix(_:)
和 hasSuffix(_:)
方法驼鞭,返回一個(gè)布爾值秦驯。舉個(gè)羅密歐與朱麗葉的?? :
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"
]
// 初始化數(shù)組
使用hasPrefix(_:)
方法計(jì)算數(shù)組中前綴為"Act 1"的數(shù)量:
var act1SceneCount = 0
for scene in romeoAndJuliet {
if scene.hasPrefix("Act 1 ") {
++act1SceneCount
}
}
print("There are \(act1SceneCount) scenes in Act 1")
// 結(jié)果為: "There are 5 scenes in Act 1"
使用hasSuffix(_:)
方法計(jì)算數(shù)組中后綴為"Capulet’s mansion"和"Friar Lawrence’s cell"的數(shù)量:
var mansionCount = 0
var cellCount = 0
for scene in romeoAndJuliet {
if scene.hasSuffix("Capulet's mansion") {
++mansionCount
} else if scene.hasSuffix("Friar Lawrence's cell") {
++cellCount
}
}
print("\(mansionCount) mansion scenes; \(cellCount) cell scenes")
// 結(jié)果為: "6 mansion scenes; 2 cell scenes"