-4

Lets say I have a Swift string

"Hello I'm John Doe"

I want to replace John Doe with:

Steve.

How is that done with Swift 3? The syntax is taking me forever to figure out.

I've tried a few things, one of them is x.replaceSubrange, but it has a syntax that I'm not able to figure out.

x?.replaceSubrange(<#T##bounds: Range##Range#>, with: <#T##String#>)

I tried to create a range with NSRange, but it didn't like that either.

mskw
  • 10,063
  • 9
  • 42
  • 64

2 Answers2

1

So you want to remove the substring after I'm and then append another string.

let original = "Hello I'm John Doe"
let marker = "I'm"
let newName = "Steve"

guard let startIndex = original.range(of: marker) else { fatalError() }
let result = "\(original.substring(with: startIndex)) \(newName)

// "I'm Steve"
Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148
0
let s1 = "Hello I'm John Doe"

//Get the start of `John Doe`
if let index = s1.range(of: "John Doe", options: .literal) {
    // Take the string from start until `John Doe` append `Steve.` to it
    let s2 = s1.substring(to: index.lowerBound).appending("Steve.")
}
TedMeftah
  • 1,845
  • 1
  • 21
  • 29
  • This works, but not what I'm looking for, but given my question seem a bit ambiguous, this is the most correct one. – mskw May 29 '17 at 18:05