swift replace first occurrence of a String

Viewed 687

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.

1 Answers

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"))
 }
Related