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?
A Swift 3 solution along the lines of Sunkas's:
Use:
Output:
Swift extension:
Go on and use it like
let replacedString = yorString.stringByReplacing(replaceStrings: [" ","?","."], with: "+")
The speed of the function is something that i can hardly be proud of, but you can pass an array of
String
in one pass to make more than one replacement.If you don't want to use the Objective-C
NSString
methods, you can just usesplit
andjoin
:split(string, isSeparator: { $0 == " " })
returns an array of strings (["This", "is", "my", "string"]
).join
joins these elements with a+
, resulting in the desired output:"This+is+my+string"
.