I am looking for a way to replace characters in a Swift String
.
Example: \"This is my string\"
I would like to replace \" \" with \"+\" to get \
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:
extension String {
mutating func replaceOccurrences(of target: Target, with replacement: Replacement, options: String.CompareOptions = [], locale: Locale? = nil) {
var range: Range?
repeat {
range = self.range(of: target, options: options, range: range.map { self.index($0.lowerBound, offsetBy: replacement.count)..
(The method signature also mimics the signature of the built-in String.replacingOccurrences()
method)
May be used in the following way:
var string = "this is a string"
string.replaceOccurrences(of: " ", with: "_")
print(string) // "this_is_a_string"