I am looking for a way to replace characters in a Swift String.
In this example String: "This is my string"
I would like to replace the spaces, " ", with "+" to end up with "This+is+my+string".
How can I achieve this?
You have a couple of options. In iOS 16 and later, String conforms to RangeReplaceableCollection, meaning you can use the replacing(_:maxReplacements:with:) instance method to achieve this.
"This is my string with spaces".replacing(" ", with: "+") // Outputs: "This+is+my+string+with+spaces"
Note that there is an optional maxReplacements argument which allows you to specify how many replacements should occur. For example:
"This is my string with spaces".replacing(" ", with: "+", maxReplacements: 2) // Outputs: "This+is+my string with spaces"
You can use the replacingOccurrences(of:with:) instance method of NSSString, which is bridged to Swift's String.
let aString = "This is my string with spaces"
let newString = aString.replacingOccurrences(of: " ", with: "+", options: .literal, range: nil) // Outputs: "This+is+my+string+with+spaces"
Note that the options and range 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.
let aString = "This is my string with spaces"
let newString = aString.replacingOccurrences(of: " ", with: "+")
You can see more examples in my article on the same subject.