美文网首页
取出字符串中数字

取出字符串中数字

作者: 你是真的很皮 | 来源:发表于2021-08-10 17:27 被阅读0次
//第一种:
extension RangeReplaceableCollection where Self: StringProtocol {
    var digits: Self {
        return filter({ $0.isNumber })
    }
}
//使用
"abc12345".digits   // "12345"

//第二种:
extension RangeReplaceableCollection where Self: StringProtocol {
    mutating func removeAllNonNumeric() {
        removeAll { !$0.isNumber }
    }
}
//使用:
var str = "123abc0"
str.removeAllNonNumeric()
print(str) //"1230"

相关文章

网友评论

      本文标题:取出字符串中数字

      本文链接:https://www.haomeiwen.com/subject/rtkfbltx.html