How can I replace a specific char with a string?

I tried to replace a specific char with a string. I want to replace the second o

with e

. I tried using:

  var s   = "bolo"
  var charIndex = advance(1, 1)
  s.replaceRange(Range(start: charIndex, end: charIndex), with: "e")
  println(s)

      

+3


source to share


2 answers


You just need to specify the startIndex (s.startIndex) string when used beforehand as shown below:



var s = "bolo"
let charIndex = advance(s.startIndex, 3)
s.replaceRange(charIndex...charIndex, with: "e")
println(s)  // "bole"

      

+3


source


You can also use the stringByReplacingOccurrencesOfString function like this:

var s = "bolooooooo"
s.stringByReplacingOccurrencesOfString("o", withString: "e", options: NSStringCompareOptions.LiteralSearch, range: Range<String.Index>(start: advance(s.startIndex, 2), end: s.endIndex))

      



Output:

boleeeeeee

      

+3


source







All Articles