Fabian Stiewe
Fabian Stiewe

Reputation: 350

swift replace first occurrence of a String

I have the String "Das Auto ist blau, das andere ist allerdings blau"

I am trying to replace only the first "blau" with "red".

I have tried it with .replacingOccurrences, but this does not work for me.

Upvotes: 7

Views: 3991

Answers (2)

Waqar Ahmed
Waqar Ahmed

Reputation: 150

extension String {

    public func replaceFirstExpression(of pattern:String,
                                   with replacement:String) -> String {
        if let range = self.range(of: pattern) {
            return self.replacingCharacters(in: range, with: replacement)
        } else {
            return self
        }
    }
}

Upvotes: 1

Shehata Gamal
Shehata Gamal

Reputation: 100503

You can try

 let str = "Das Auto ist blau, das andere ist allerdings blau"
 if let range = str.range(of:"blau") {
     print(str.replacingCharacters(in: range, with:"red"))
 }

Upvotes: 10

Related Questions