skip to Main Content

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


  1. 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 characters

    let str1 = "1:22 PM"
    let keeping = String(str1.filter{$0.isLetter || $0.isNumber})
    
    Login or Signup to reply.
  2. This is a String extension I used on another project I worked on. I think it can help with what you are trying to achieve:

    extension String {
        func keepingCharacters(in characterSets: [CharacterSet]) -> String {
            let combinedCharacterSet = characterSets.reduce(CharacterSet()) { $0.union($1) }
            return String(self.filter { combinedCharacterSet.contains(UnicodeScalar(String($0))!) })
        }
    }
    

    This way I could specify what I wanted to keep, but if you only want to keep .alphanumerics you can adapt it easily.

    "1:22 PM".keepingCharacters(in: [.alphanumerics, .punctuationCharacters, .whitespaces])
    //"1:22 PM"
    
    "1:22 PM".keepingCharacters(in: [.alphanumerics, .whitespaces])
    //"122 PM"
    
    "1:22 PM".keepingCharacters(in: [.alphanumerics])
    //"122PM"
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search