我试图替换字符串中的特定字符。我想替换o
的借调e
。我试过用:
var s = "bolo"
var charIndex = advance(1, 1)
s.replaceRange(Range(start: charIndex, end: charIndex), with: "e")
println(s)
答案 0 :(得分:3)
你需要在使用advance时指定字符串startIndex(s.startIndex),如下所示:
var s = "bolo"
let charIndex = advance(s.startIndex, 3)
s.replaceRange(charIndex...charIndex, with: "e")
println(s) // "bole"
答案 1 :(得分:3)
您也可以通过以下方式使用函数stringByReplacingOccurrencesOfString:
var s = "bolooooooo"
s.stringByReplacingOccurrencesOfString("o", withString: "e", options: NSStringCompareOptions.LiteralSearch, range: Range<String.Index>(start: advance(s.startIndex, 2), end: s.endIndex))
输出结果为:
boleeeeeee