wasimsandhu
wasimsandhu

Reputation: 4555

swift - using replaceRange() to change certain occurrences in a string

Say I have a string, and I want to change the first "a" in that string to an "e" in order to get the correct spelling.

let animal = "elaphant"

Using stringByReplacingOccurrencesOfString() will change every "a" in that string to an "e", returning:

elephent

I am trying to get the index of the first "a" and then replacing it using replaceRange(), like so:

let index = animal.characters.indexOf("a")
let nextIndex = animal.startIndex.distanceTo(index!)
animal = animal.replaceRange(animal.startIndex.advancedBy(nextIndex)..<animal.startIndex.advancedBy(1), with: "e")

However, this code gives me the following error:

Cannot assign value of type '()' to type 'String'

I have been trying to find a way to convert nextIndex into an Int, but I feel like I've got this whole method wrong. Help?

Upvotes: 11

Views: 26669

Answers (4)

Leo Dabus
Leo Dabus

Reputation: 236360

update:

Swift 4.2 or later

var animal = "elaphant"
if let index = animal.firstIndex(of: "a") {
    animal.replaceSubrange(index...index, with: ["e"])
}

We can extend RangeReplaceableCollection Protocol and create our own replaceFirstOccurrence(of: Element) method:

extension RangeReplaceableCollection where Element: Equatable {
    mutating func replaceFirstOccurrence(of element: Element, with replacement: Element) {
        guard let index = firstIndex(of: element) else { return }
        replaceSubrange(index...index, with: CollectionOfOne(replacement))
    }
    func replacingFirstOccurrence(of element: Element, with replacement: Element) -> Self {
        var elements = self
        elements.replaceFirstOccurrence(of: element, with: replacement)
        return elements
    }
}

var animal = "elaphant"

// non mutating method
print(animal.replacingFirstOccurrence(of: "a", with: "e"))  // elephant
print(animal)     // still "elaphant"

// mutating method
animal.replaceFirstOccurrence(of: "a", with: "e")
print(animal)    // mutated to "elephant"

Upvotes: 6

Tanin
Tanin

Reputation: 595

Swift4

var animal = "elaphant"

if let index = animal.index(of: "a") {
    animal.replaceSubrange(index...index, with: "e")
}

print (animal) // elephant

Upvotes: 0

Blake Lockley
Blake Lockley

Reputation: 2961

This is is what you want to do:

var animal = "elaphant"
if let range = animal.rangeOfString("a") {
  animal.replaceRange(range, with: "e")
}

rangeOfString will search for the first occurrence of the provided substring and if that substring can be found it will return a optional range otherwise it will return nil.

we need to unwrap the optional and the safest way is with an if let statement so we assign our range to the constant range.

The replaceRange will do as it suggests, in this case we need animal to be a var.

Upvotes: 9

iYoung
iYoung

Reputation: 3622

Tested in Playground:

var animal = "elaphant"
if let range = animal.rangeOfString("a") {
animal.replaceRange(range, with: "e")
}

print (animal)

Upvotes: 0

Related Questions