如何在 Swift 4 中过滤字符串中的字符 [英] How to filter characters from a string in Swift 4
本文介绍了如何在 Swift 4 中过滤字符串中的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在下面的 Swift 3 代码中,我从字符串中提取所有数字,但我不知道如何在 Swift 4 中做同样的事情.
In the following Swift 3 code I'm extracting all numbers from a string but I can not figure out how to do the same thing in Swift 4.
var myString = "ABC26FS464"
let myNumbers = String(myString.characters.filter { "01234567890".characters.contains($0)})
print(myNumbers) // outputs 26464
如何在 Swift 4 中从字符串中提取所有数字?
How can I extract all numbers from a string in Swift 4?
推荐答案
Swift 4 让它变得更简单一些.只需删除 .characters 并使用
Swift 4 makes it a little simpler. Just remove the .characters and use
let myNumbers = myString.filter { "0123456789".contains($0) }
但要真正做到正确,您可能会使用decimalDigits 字符集...
But to really do it properly, you might use the decimalDigits character set...
let digitSet = CharacterSet.decimalDigits
let myNumbers = String(myString.unicodeScalars.filter { digitSet.contains($0) })
这篇关于如何在 Swift 4 中过滤字符串中的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文