我有一个包含字符和浮点值的字符串,在列表中,例如let string =“ 12.1gh34.5abc32.1”。我想从字符串中删除字符,结果将以浮点值显示在数组中。有什么解决办法吗?
答案 0 :(得分:3)
使用字母作为分隔符分割字符串。从结果中删除空字符串。将剩余的数字字符串映射为实数。
let string = "12.1gh34.5abc32.1"
let numbers = string.components(separatedBy: .letters)
.filter { !$0.isEmpty }
.compactMap { Double($0) }
输出为:
[12.1,34.5,32.1]
如果要处理非十进制数字或逗号的内容,可以将.letters
替换为:
CharacterSet(charactersIn: "0123456789.").inverted
答案 1 :(得分:0)
您可以使用集合split
方法并将omittingEmptySubsequences
设置为true
:
extension StringProtocol {
func notContains(_ element: Element) -> Bool {
return !contains(element)
}
var numbers: [SubSequence] {
return split(maxSplits: Int.max, omittingEmptySubsequences: true, whereSeparator: "0123456789.".notContains)
}
}
let text = "12.1gh 34.5abc 32.5"
let result = text.numbers // ["12.1", "34.5", "32.5"]
let nums = result.flatMap(Double.init) // [12.1, 34.5, 32.5]