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?
You can use this:
If you add this extension method anywhere in your code:
Swift 3:
Did you test this :
A category that modifies an existing mutable String:
Use:
This answer has been updated for Swift 4. If you're still using Swift 1, 2 or 3 see the revision history.
You have a couple of options. You can do as @jaumard suggested and use
replacingOccurrences()
And as noted by @cprcrack below, the
options
andrange
parameters are optional, so if you don't want to specify string comparison options or a range to do the replacement within, you only need the following.Or, if the data is in a specific format like this, where you're just replacing separation characters, you can use
components()
to break the string into and array, and then you can use thejoin()
function to put them back to together with a specified separator.Or if you're looking for a more Swifty solution that doesn't utilize API from NSString, you could use this.
Swift 3, Swift 4 Solution
I am using this extension:
Usage: