Reputation: 2788
I have tried to replace a specific char in a string. I want to replace the the seconde o
for an e
. I have tried to use:
var s = "bolo"
var charIndex = advance(1, 1)
s.replaceRange(Range(start: charIndex, end: charIndex), with: "e")
println(s)
Upvotes: 3
Views: 152
Reputation: 23449
You can use too the function stringByReplacingOccurrencesOfString, in the following way:
var s = "bolooooooo"
s.stringByReplacingOccurrencesOfString("o", withString: "e", options: NSStringCompareOptions.LiteralSearch, range: Range<String.Index>(start: advance(s.startIndex, 2), end: s.endIndex))
The output is :
boleeeeeee
Upvotes: 3
Reputation: 236528
You just need to specify the string startIndex (s.startIndex) when using advance as follow:
var s = "bolo"
let charIndex = advance(s.startIndex, 3)
s.replaceRange(charIndex...charIndex, with: "e")
println(s) // "bole"
Upvotes: 3