In Swift is there an opposite/complement to String.trimmingCharacters(in: CharacterSet)
, something like keepingCharacters(in: CharacterSet)
.
Instead of removing characters from CharacterSet
like trimmingCharacters
does, keepingCharacters
should keep characters from CharacterSet
and remove all characters not present in the CharacterSet
.
eg:
let str1 = "1:22 PM"
let keeping = str1.keepingCharacters(in: .alphanumerics)
// should return "122PM"
2
Answers
Strictly spoken this is not a complement because the function
trimmingCharacters
removes only characters from the beginning and end of the string.A possible way is to
filter
unwanted charactersThis is a
String
extension I used on another project I worked on. I think it can help with what you are trying to achieve:This way I could specify what I wanted to keep, but if you only want to keep
.alphanumerics
you can adapt it easily.