? ? 我們可以通過調(diào)用方法,屬性或者下標去訪問或者修改字符串。
字符串索引
? ? 每一個字符串都有一個相關(guān)聯(lián)的索引類型,String.index,對應于字符串中每個字符的位置。
? ? 如上一章所述,不同的字符需要不同的空間去存儲,因此位了確定處于特定位置的字符,需要從起始遍歷一次字符串。也就是因為這個原因,Swift中的String無法用整型值進行索引。
? ? 使用屬性startIndex可以訪問字符串第一個字符的位置,使用屬性endIndex可以訪問字符串最后一個字符的位置。屬性endIndex無法作為字符串下標的參數(shù)。如果字符串是空的,startIndex等于endIndex。
? ? 如果希望獲取一個已知索引的前面或者后面的索引,可以使用字符串提供的index(before:)方法和index(after:)方法。要訪問某個遠離已知索引的索引,可以使用index(_:offsetBy:)方法,而不需要多次調(diào)用前述的方法。
? ? 可以使用下標的語法獲取字符串某個特定索引的字符。
? ??????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
? ? 獲取超過字符串范圍的索引或者不在字符串中的某個字符會導致一個運行時錯誤:
? ??????greeting[greeting.endIndex] // Error
????????greeting.index(after: greeting.endIndex) // Error
? ? 通過屬性indices可以獲取字符串中每一個字符的索引:
? ??????for index in greeting.indices {
????????? ? print("\(greeting[index]) ", terminator: "")
????????}
????????// 打印 "G u t e n? T a g !?
NOTE:實現(xiàn)了Collection協(xié)議的類都提供了屬性startIndex和endIndex以及方法index(before:), index(after:), 和 index(_:offsetBy:)。當然包括這里的String,還有Array,Dictionary,Set等。
插入和刪除
? ? 在字符串特定的位置插入一個字符,可以使用方法insert(_:at:),在特定的位置插入另外一個字符串,可以使用方法insert(contentsOf:at:) 。
? ??????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!”
? ? 要移除一個字符串特定位置的字符,使用方法remove(at:),要移除一個特定范圍內(nèi)的子字符串,使用方法removeSubrange(_:)。
? ??????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”
NOTE:實現(xiàn)了RangeReplaceableCollection協(xié)議的類都提供了方法insert(_:at:), insert(contentsOf:at:), remove(at:), and removeSubrange(_:)。當然包括這里的String,還有Array,Dictionary,Set等。