![](/img/trans.png)
[英]swift - using replaceRange() to change certain occurrences in a string
[英]How does the Swift String replaceRange method deal with empty ranges
是否期望在對Swift字符串調用replaceRange
時,其范圍具有相同的開始和結束索引,而replaceRange
方法將插入一個新字符並使該字符串更長?
例如,使用此方法:
func replaceCharAtPositionForWord(word:String, position: Int, char: Character) -> String {
var newWord : String = word;
var range : Range = Range<String.Index>(start: advance(newWord.startIndex, position),
end:advance(newWord.startIndex, position+1))
newWord.replaceRange(range, with: String(char))
return newWord;
}
調用replaceCharAtPositionForWord("Hello", 3, Character("a"))
返回預期的“ Helao”。
但是,如果將上述Range
設置為:
var range : Range = Range<String.Index>(start: advance(newWord.startIndex, position),
end:advance(newWord.startIndex, position))
然后代碼插入一個新字符並將字符串結果擴展為“ Helalo”
這是沒有長度的Range
所期望的嗎?
您應該設置開始位置和結束位置:
text?.replaceRange(
(text?.startIndex.advancedBy(
range.location // start position
))!..<(text?.startIndex.advancedBy(
range.location + range.length // end position
))!,
with: string)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.