1. 程式人生 > >Swift學習筆記(4):字符串

Swift學習筆記(4):字符串

min mes 不同的 常用方法 dice 內存空間 全部 there logs

目錄:

  • 初始化
  • 常用方法或屬性
  • 字符串索引

初始化

創建一個空字符串作為初始值:

var emptyString = ""                // 空字符串字面量
var anotherEmptyString = String()   // 初始化方法,兩個字符串均為空並等價。

常用方法或屬性
 1 var empty = emptyString.isEmpty    // 判斷字符串是否為空
 2 var welcome = "string1" + string2  // 使用 + 或 += 拼接字符串
 3 welcome.append("character
") // 使用append()在字符串末尾追加字符 4 5 // 使用 \(變量) 進行字符串插值 6 let multiplier = 3 7 let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)" 8 9 // 使用 == 或 != 進行字符串比較 10 if quotation == sameQuotation { 11 print("These two strings are considered equal") 12 } 13 14 // 使用 hasPrefix() 和 hasSuffix() 判斷是否又前綴或後綴
15 if scene.hasPrefix("Act 1 ") { 16 print("The string has the prefix of Act 1“) 17 }

註意:

?不能將一個字符串或者字符添加到一個已經存在的字符變量上,因為字符變量只能包含一個字符。
?插值字符串中寫在括號中的表達式不能包含非轉義反斜杠 ( \ ),並且不能包含回車或換行符。

字符串索引

可以通過字符串下標或索引屬性和方法來訪問和修改它,String.Index對應著字符串中的Character位置。

 1 sampleString.startIndex.         //
獲取第一個字符的索引 2 sampleString.endIndex // 獲取最後一個字符的索引 3 4 let greeting = "Guten Tag!" 5 greeting[greeting.startIndex] // G 使用下標獲取字符 6 greeting[greeting.index(before: greeting.endIndex)] // ! 7 greeting[greeting.index(after: greeting.startIndex)] // u 8 9 let index = greeting.index(greeting.startIndex, offsetBy: 7) 10 greeting[index] // a 11 12 /* 13 greeting[greeting.endIndex] // error Index越界 14 greeting.index(after: endIndex) // error Index越界 15 */ 16 17 // 使用 characters.indices 屬性創建一個包含全部索引Range來遍歷字符串中單個字符 18 for index in greeting.characters.indices { 19 print("\(greeting[index]) ", terminator: "") // 輸出 "G u t e n T a g ! " 20 } 21 22 var welcome = "hello" 23 welcome.insert("!", at: welcome.endIndex) // welcome 等於 "hello!" 24 welcome.remove(at: welcome.index(before: welcome.endIndex))// welcome 等於 "hello"

註意:

?可擴展的字符群集可以組成一個或者多個Unicode標量。這意味著不同的字符以及相同字符的不同表示方式可能需要不同數量的內存空間來存儲。所以Swift中的字符在一個字符串中並不一定占用相同的內存空間。因此在沒有獲得字符串可擴展字符群集範圍的時候,是不能計算出字符串的字符數量,此時就必須遍歷字符串全部的 Unicode 標量,來確定字符數量。

聲明:該系列內容均來自網絡或電子書籍,只做學習總結!

Swift學習筆記(4):字符串