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

8ljdwjyq  于 2022-12-02  发布在  Swift
关注(0)|答案(6)|浏览(209)

How to strip special characters out of string?中的答案不起作用。
这是我得到的结果,它给了我一个错误

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

    return String(str.characters.filter { chars.contains($0) }) //error here at $0
}

$0处的错误表示
_Element(aka Character)无法转换为预期的参数类型'String'。

tcbh2hod

tcbh2hod1#

就像这样:

func removeSpecialCharsFromString(text: String) -> String {
    let okayChars : Set<Character> = 
        Set("abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLKMNOPQRSTUVWXYZ1234567890+-*=(),.:!_".characters)
    return String(text.characters.filter {okayChars.contains($0) })
}

测试方法如下:

let s = removeSpecialCharsFromString("père") // "pre"
dw1jzc5e

dw1jzc5e2#

SWIFT 4:

func removeSpecialCharsFromString(text: String) -> String {
    let okayChars = Set("abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLKMNOPQRSTUVWXYZ1234567890+-=().!_")
    return text.filter {okayChars.contains($0) }
}

更清洁的道:

extension String {

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

使用此扩展名,例如:

let myCleanString = "some.Text@#$".stripped

输出:“部分.文本”

j13ufse2

j13ufse23#

我认为一个更干净的解决方案可以是这样的方法:

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

nx7onnlm4#

试试这个:

someString.removeAll(where: {$0.isPunctuation})
qhhrdooz

qhhrdooz5#

Swift 1.2中,

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

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

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

原因是字符串本身不再符合SequenceType,您必须显式使用characters视图。
通过该更改,您的方法将按预期方式编译和工作:

func removeSpecialCharsFromString(str: String) -> String {
    let chars = Set("abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLKMNOPQRSTUVWXYZ1234567890+-*=(),.:!_".characters)
    return String(str.characters.filter { chars.contains($0) })
}

let cleaned = removeSpecialCharsFromString("ab€xy")
print(cleaned) // abxy
  • 备注:* @Kametrixom建议只创建一次集合。因此,* 如果 * 上述方法存在性能问题,您可以将集合的声明移到函数之外,或者将其设为局部static
func removeSpecialCharsFromString(str: String) -> String {
    struct Constants {
        static let validChars = Set("abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLKMNOPQRSTUVWXYZ1234567890+-*=(),.:!_".characters)
    }
    return String(str.characters.filter { Constants.validChars.contains($0) })
}
t9eec4r0

t9eec4r06#

不删除单词之间的空格

extension String {
    var removeSpecialCharacters: String {
        return self.components(separatedBy: CharacterSet.alphanumerics.inverted).filter({ !$0.isEmpty }).joined(separator: " ")
    }
}

相关问题