訪問和修改字符串

? ? 我們可以通過調(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等。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容