1 字符串字面量(String Literals)
"Some string literal value"
2 初始化空字符串 (Initializing an Empty String)
var emptyString = ""
var anotherEmptyString = String()
if emptyString.isEmpty {
print("Nothing to see here")
}
3 字符串可變性(String Mutability)
var variableString = "Horse"
variableString += " and carriage"
//let constantString = "Highlander"
//constantString += " and another Highlander"
4 字符串是值類型(Strings Are Value Types)
在實(shí)際編譯時(shí),Swift 編譯器會(huì)優(yōu)化字符串的使用,使實(shí)際的復(fù)制只發(fā)生在絕對必要的情況下鞠绰,這意味著您將字符串作為值類型的同時(shí)可以獲得極高的性能额港。
5 使用字符(Working with Characters)
for character in "Dog!???" {
print(character)
}
let exclamationMark: Character = "!" // `Character`是字符(注意也是雙引號(hào)仅淑,不是單引號(hào))
let catCharacters: [Character] = ["C", "a", "t", "!", "?"]
let catString = String(catCharacters) // 字符數(shù)組生成字符串
6 連接字符串和字符 (Concatenating Strings and Characters)
let string1 = "Hello"
let string2 = " there"
var welcome0 = string1 + string2
welcome0 += string1
welcome0.append(exclamationMark)
7 字符串插值 (String Interpolation)
插值字符串中寫在括號(hào)中的表達(dá)式不能包含非轉(zhuǎn)義雙引號(hào) (") 和反斜杠 ()牛哺,并且不能包含回車或換行符。
let multiplier = 3
let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)" // message is "3 times 2.5 is 7.5"
8 Unicode
// Swift的String和Character類型是完全兼容Unicode標(biāo)準(zhǔn)的动看。
let dollarSign = "\u{24}" // Unicode 標(biāo)量 U+0024
let blackHeart = "\u{2665}" // Unicode 標(biāo)量 U+2665
let sparklingHeart = "\u{1F496}" // Unicode 標(biāo)量 U+1F496
// 可擴(kuò)展的字形群集(Extended Grapheme Clusters)
9 計(jì)算字符數(shù)量 (Counting Characters)
welcome0.count
10 訪問和修改字符串 (Accessing and Modifying a String)
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: 6) // 從某個(gè)索引開始向后offsetBy的索引
greeting[index]
for index in greeting.indices {
print("\(greeting[index]) ", terminator: "")
}
// Inserting and Removing
var welcome = "hello"
welcome.insert("!", at: welcome.endIndex) // welcome now equals "hello!"
welcome.insert(contentsOf:" there", at: welcome.index(before: welcome.endIndex)) // welcome now equals "hello there!
welcome.remove(at: welcome.index(before: welcome.endIndex)) // welcome now equals "hello there"
let range = welcome.index(welcome.endIndex, offsetBy: -6) ..< welcome.endIndex
welcome.removeSubrange(range) // welcome now equals "hello"
11 比較字符串 (Comparing Strings)
12 字符串的 Unicode 表示形式(Unicode Representations of Strings)
13 String的常見方法和屬性
//welcome.characters // `String`沒有繼承`Sequence`裕偿,不能直接遍歷洞慎,用 `String.characters`
welcome.count
for c in welcome {
}
welcome.isEmpty
welcome.startIndex
welcome.hashValue
welcome.hasPrefix("he") // 是否有前綴
welcome.hasSuffix("!") // 是否有后綴
welcome.lowercased() // 變成小寫
welcome.uppercased() // 變成大寫
playground文件在andyRon/LearnSwift