對應可變字符串可以插入、刪除和替換,String提供了幾個方法可以幫助實現這些操作。這些方法如下:
splice(_:atIndex:)。在索引位置插入字符串。
insert(_:atIndex:)。在索引位置插入字符。
removeAtIndex(_:)。在索引位置刪除字符。
removeRange(_:)。刪除指定范圍內的字符串。
replaceRange(_:,with: String) 。使用字符串或字符替換指定范圍內的字符串。
代碼:
var str ="Swift"
print("原始字符串:\(str)")
str.splice("Objective-Cand ".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-Cand Swift.
刪除.字符后:Objective-Cand Swift
刪除范圍后:C and Swift
替換范圍后:C++ and Swift
