我是Swift Programming的新手。我想问一下是否有人可以帮我从字符串中只返回字母数字子字符串?
示例:
输入=“狼与狮子”
输出=“wolflion”
我想知道除了正则表达式之外是否有任何解决方案 谢谢
答案 0 :(得分:1)
试试这个:
let outputStr = "wolf & lion".components(separatedBy: CharacterSet.alphanumerics.inverted)
.joined()
print(outputStr)//wolflion
答案 1 :(得分:0)
var a = "abs1 2csd^!@awerqwe"
let b = a.characters.map { (char) -> String in
if let charRange = String(char).rangeOfCharacter(from: CharacterSet.alphanumerics) {
return String(char)
} else {
return ""
}
}.joined()
//OR use unicode scalar
let c = a.unicodeScalars.map { (char) -> String in
if CharacterSet.alphanumerics.contains(char) {
return String(char)
} else {
return ""
}
}.joined()
输出:abs12csdawerqwe
答案 2 :(得分:0)
请检查:
let str = "wolf & lion"
let charset = str.trimmingCharacters(in: CharacterSet.alphanumerics)
let alphanumericString = str.components(separatedBy: charset).joined(separator: "")
print(alphanumericString) // wolflion