如何从字符串中去除特殊字符的答案?不管用。
这是我得到的,它给我一个错误
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提示
$0
_Element(aka字符)无法转换为预期的参数类型’String’。
像这样:
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"