Reputation: 103
Hi I would like to build a function which will replace all the special character ie: * & ! @ # $ % with "//(with whatever the match will be)
so I string like "1*234@" will become 1//*/234//@"
is there a replace function in swift to do that?
Upvotes: 0
Views: 820
Reputation: 16327
String.replacingOccurrences which can be used like so:
let replacements = ["!" : "-exclamation-", "." : "-period-"]
var stringToModify = "hello! This is a string."
replacements.keys.forEach { stringToModify = stringToModify.replacingOccurrences(of: $0, with: replacements[$0]!)}
print(stringToModify)
output: hello -exclamation- This is a string -period-
There is also an overload with more options, incase you want to do stuff like case insensitive compare. https://developer.apple.com/reference/foundation/nsstring/1416484-replacingoccurrences
Upvotes: 1