ios 如何从 Swift 2 中的字符串中删除特殊字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32851720/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 07:52:13  来源:igfitidea点击:

How to remove special characters from string in Swift 2?

iosstringswift

提问by Harout360

The answer in How to strip special characters out of string?is not working.

在回答 如何剥离特殊字符串出的?不管用。

Here is what I got and it gives me an error

这是我得到的,它给了我一个错误

func removeSpecialCharsFromString(str: String) -> String {
    let chars: Set<String> = Set(arrayLiteral: "abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLKMNOPQRSTUVWXYZ1234567890+-*=(),.:!_")

    return String(str.characters.filter { chars.contains(
func removeSpecialCharsFromString(text: String) -> String {
    let okayChars : Set<Character> = 
        Set("abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLKMNOPQRSTUVWXYZ1234567890+-*=(),.:!_".characters)
    return String(text.characters.filter {okayChars.contains(
let s = removeSpecialCharsFromString("père") // "pre"
) }) }
) }) //error here at
func removeSpecialCharsFromString(text: String) -> String {
    let okayChars = Set("abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLKMNOPQRSTUVWXYZ1234567890+-=().!_")
    return text.filter {okayChars.contains(
extension String {

    var stripped: String {
        let okayChars = Set("abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLKMNOPQRSTUVWXYZ1234567890+-=().!_")
        return self.filter {okayChars.contains(
let myCleanString = "some.Text@#$".stripped
) } } }
) } }
}

The error at $0says

错误在$0

_Element (aka Character) cannot be converted to expected argument type 'String'.

_Element(又名字符)无法转换为预期的参数类型“字符串”。

回答by matt

Like this:

像这样:

extension String {
    var alphanumeric: String {
        return self.components(separatedBy: CharacterSet.alphanumerics.inverted).joined().lowercased()
    }
}

And here's how to test:

以下是测试方法:

let chars = Set("abcde...")

回答by Maksim Kniazev

SWIFT 4:

快速 4:

let chars = Set("abcde...".characters)

More cleaner way:

更干净的方式:

func removeSpecialCharsFromString(str: String) -> String {
    let chars = Set("abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLKMNOPQRSTUVWXYZ1234567890+-*=(),.:!_".characters)
    return String(str.characters.filter { chars.contains(
func removeSpecialCharsFromString(str: String) -> String {
    struct Constants {
        static let validChars = Set("abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLKMNOPQRSTUVWXYZ1234567890+-*=(),.:!_".characters)
    }
    return String(str.characters.filter { Constants.validChars.contains(
extension RangeReplaceableCollection where Self: StringProtocol {
    var asciiPrintable: Self { filter { 
let string = "cafe\u{301}"
let asciiPrintable = string.asciiPrintable
print(asciiPrintable)  // "caf"
.isASCII && 32..<127 ~= (
someString.removeAll(where: {##代码##.isPunctuation})
.unicodeScalars.first?.value ?? 0) } } }
) }) }
) }) } let cleaned = removeSpecialCharsFromString("abxy") print(cleaned) // abxy

Use this extension like:

使用此扩展程序,如:

##代码##

Output: "some.Text"

输出:“some.Text”

回答by Bisca

I think that a cleaner solution could be this approach:

我认为更清洁的解决方案可能是这种方法:

##代码##

回答by Martin R

In Swift 1.2,

Swift 1.2 中,

##代码##

created a set containing all characters from the given string. In Swift 2.0this has to be done as

创建了一个包含给定字符串中所有字符的集合。在Swift 2.0中,必须这样做

##代码##

The reason is that a string itself does no longer conform to SequenceType, you have to use the charactersview explicitly.

原因是字符串本身不再符合 SequenceType,您必须characters显式使用视图。

With that change, your method compiles and works as expected:

通过该更改,您的方法将按预期编译并运行:

##代码##

Remark:@Kametrixom suggested to create the set only once. So ifthere is performance issue with the above method you can either move the declaration of the set outside of the function, or make it a local static:

备注:@Kametrixom 建议只创建一次集合。因此,如果上述方法存在性能问题,您可以将 set 的声明移到函数之外,或者使其成为 local static

##代码##

回答by Leo Dabus

If you need to keep only ascii printable characters in a string you can just filter them checking if their unicodeScalar values are ascii:

如果您只需要在字符串中保留 ascii 可打印字符,您可以过滤它们,检查它们的 unicodeScalar 值是否为 ascii:

##代码##

##代码##

回答by Ben Lin

Try this:

尝试这个:

##代码##