How to strip special characters out of string?

Roberto picture Roberto · Mar 2, 2015 · Viewed 8.4k times · Source

I have a set with the characters I allow in my string:

var characterSet:NSCharacterSet = NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ")

I want to strip any other characters from a string so two unformatted data can be considered equal, like this:

"American Samoa".lowercaseString == "american_samoa1".lowercaseString

the lowercase version of these transformed strings would be "americansamoa"

Answer

mustafa picture mustafa · Mar 2, 2015

Let's write a function for that (in swift 1.2).

func stripOutUnwantedCharactersFromText(text: String, set characterSet: Set<Character>) -> String {
    return String(filter(text) { set.contains($0) })
}

You can call it like that:

let text = "American Samoa"
let chars = Set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
let strippedText = stripOutUnwantedCharactersFromText(text, set: chars)

Pure swift. Yeah.