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 \
I am using this extension:
extension String {
func replaceCharacters(characters: String, toSeparator: String) -> String {
let characterSet = NSCharacterSet(charactersInString: characters)
let components = self.componentsSeparatedByCharactersInSet(characterSet)
let result = components.joinWithSeparator("")
return result
}
func wipeCharacters(characters: String) -> String {
return self.replaceCharacters(characters, toSeparator: "")
}
}
Usage:
let token = "<34353 43434>"
token.replaceCharacters("< >", toString:"+")
Xcode 11 • Swift 5.1
The mutating method of StringProtocol replacingOccurrences
can be implemented as follow:
extension RangeReplaceableCollection where Self: StringProtocol {
mutating func replaceOccurrences<Target: StringProtocol, Replacement: StringProtocol>(of target: Target, with replacement: Replacement, options: String.CompareOptions = [], range searchRange: Range<String.Index>? = nil) {
self = .init(replacingOccurrences(of: target, with: replacement, options: options, range: searchRange))
}
}
var name = "This is my string"
name.replaceOccurrences(of: " ", with: "+")
print(name) // "This+is+my+string\n"
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<Target: StringProtocol, Replacement: StringProtocol>(of target: Target, with replacement: Replacement, options: String.CompareOptions = [], locale: Locale? = nil) {
var range: Range<Index>?
repeat {
range = self.range(of: target, options: options, range: range.map { self.index($0.lowerBound, offsetBy: replacement.count)..<self.endIndex }, locale: locale)
if let range = range {
self.replaceSubrange(range, with: replacement)
}
} while range != nil
}
}
(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"
A category that modifies an existing mutable String:
extension String
{
mutating func replace(originalString:String, withString newString:String)
{
let replacedString = self.stringByReplacingOccurrencesOfString(originalString, withString: newString, options: nil, range: nil)
self = replacedString
}
}
Use:
name.replace(" ", withString: "+")
var str = "This is my string"
str = str.replacingOccurrences(of: " ", with: "+")
print(str)
Here is the example for Swift 3:
var stringToReplace = "This my string"
if let range = stringToReplace.range(of: "my") {
stringToReplace?.replaceSubrange(range, with: "your")
}