iosswiftstringreplace

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.


Solution

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