Reputation: 350
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
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
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