如何在SWIFT中从主字符串拆分数字和子字符串?

我有一种情况,需要从主给定字符串中分离数值和其他子字符串。

Suppose the main string is 350.55kph. Then my desired result is 350.55 as a numeric value and kph is other substring.

有人可以帮我弄这个吗?

评论
eut
eut

方法如下:

let string = "350kph"
let stringArray = string.components(separatedBy: CharacterSet.decimalDigits.inverted)
for item in stringArray {
    if let integer = Int(item) {
        print("integer: \(integer)")
    }
}

Note: This would work for strings containing multiple Int eg: "350km per 2hr". You would only require:

let string = "350kph"
let integer = Int(string.components(separatedBy: CharacterSet.decimalDigits.inverted).joined())
print("integer: \(integer)")
点赞
评论