How to strip special characters out of string?

家住魔仙堡 提交于 2019-12-04 15:27:10
mustafa

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.

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.

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"

Swift 3 upgraded answer:

let jpegName = "<Hit'n'roll>.jpg"
let disallowedChars = CharacterSet.urlPathAllowed.inverted
let fileName = fileName.components(separatedBy: disallowedChars).joined(separator: "_")

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()
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!