2

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"

Christian
  • 22,585
  • 9
  • 80
  • 106
Roberto
  • 11,557
  • 16
  • 54
  • 68

5 Answers5

9

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.

Donnelle
  • 5,689
  • 3
  • 27
  • 31
mustafa
  • 15,254
  • 10
  • 48
  • 57
3

You were on the right track. But you can use the invertedSet on your NSCharSet. That means you allow every character you set in your NSCharSet, because it's easier to do that way. Otherwise you'd need to check every char you don't want to allow which are many more than set the allowed ones:

var charSet = NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ").invertedSet
var unformatted = "american_samoa1"
var cleanedString = join("", unformatted.componentsSeparatedByCharactersInSet(charSet))

println(cleanedString) // "americansamoa"

As you see, I use the join method on the created array. I do that because you really want a string and otherwise you'd have a array of strings.

Christian
  • 22,585
  • 9
  • 80
  • 106
3

Updated the below example for Swift 2.3 to replace the join method.

let charSet = NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ").invertedSet
let unformatted = "american_samoa1"
let cleanedString = unformatted.componentsSeparatedByCharactersInSet(charSet)).joinWithSeparator("")

print(cleanedString) // "americansamoa"
Frankie
  • 11,508
  • 5
  • 53
  • 60
3

Swift 3 upgraded answer:

let jpegName = "<Hit'n'roll>.jpg"
let disallowedChars = CharacterSet.urlPathAllowed.inverted
let fileName = fileName.components(separatedBy: disallowedChars).joined(separator: "_")
192kb
  • 646
  • 8
  • 15
2

This currently works for swift 3.X

func strip(unformatted: String) -> String {
    let disallowedChars = CharacterSet.letters.inverted
    let formatted = unformatted.components(separatedBy: disallowedChars).joined(separator: "")
    return formatted.lowercased()
}
D.McGrath
  • 21
  • 4