《從零開始學Swift》學習筆記(Day 14)——字串的插入、刪除和替換

智捷關東昇發表於2016-03-14

原創文章,歡迎轉載。轉載請註明:關東昇的部落格

  對應可變字串可以插入、刪除和替換,String提供了幾個方法可以幫助實現這些操作。這些方法如下:
    splice(:atIndex:)。在索引位置插入字串。
   insert(
:atIndex:)。在索引位置插入字元。
    removeAtIndex(:)。在索引位置刪除字元。
   removeRange(
:)。刪除指定範圍內的字串    replaceRange(_:, with: String) 。使用字串或字元替換指定範圍內的字串。
  程式碼:

var str = "Swift"
print("原始字串:\(str)")

str.splice("Objective-C and ".characters, atIndex: str.startIndex)     
print("插入字串後:\(str)")

str.insert(".", atIndex: str.endIndex)        
print("插入.字元後:\(str)")

str.removeAtIndex(str.endIndex.predecessor())
print("刪除.字元後:\(str)")

var startIndex = str.startIndex                
var endIndex = advance(startIndex, 9)        
var range = startIndex...endIndex        

str.removeRange(range)                    
print("刪除範圍後:\(str)")

startIndex = str.startIndex
endIndex = advance(startIndex, 0)
range = startIndex...endIndex        

str.replaceRange(range, with: "C++")    

print("替換範圍後:(str)")

  輸出結果:
    原始字串:Swift
    插入字串後:Objective-C and Swift
    插入.字元後:Objective-C and Swift.
    刪除.字元後:Objective-C and Swift
    刪除範圍後:C and Swift
    替換範圍後:C++ and Swift

歡迎關注關東昇新浪微博@tony_關東昇。 關注智捷課堂微信公共平臺,瞭解最新技術文章、圖書、教程資訊

enter image description here

更多精品iOS、Cocos、移動設計課程請關注智捷課堂官方網站:http://www.zhijieketang.com 智捷課堂論壇網站:http://51work6.com/forum.php

相關文章