I'm looking for a way to replace characters in a Swift String
.
Example: "This is my string"
I'd like to replace with
+
to get: "This+is+my+string"
.
How can I achieve this?
I'm looking for a way to replace characters in a Swift String
.
Example: "This is my string"
I'd like to replace with
+
to get: "This+is+my+string"
.
How can I achieve this?
Swift 4:
Output:
Here is the example for Swift 3:
I think Regex is the most flexible and solid way:
Swift 3 solution based on Ramis' answer:
Tried to come up with an appropriate function name according to Swift 3 naming convention.
Here's an extension for an in-place occurrences replace method on
String
, that doesn't no an unnecessary copy and do everything in place:(The method signature also mimics the signature of the built-in
String.replacingOccurrences()
method)May be used in the following way:
I've implemented this very easy func:
So you can write: