我遇到的一个问题是,如果我使用解析字符串作为计算器程序的结果,例如,
4.5 * 5.0 = 22.5
我如何在这里使用拆分来从结果中分离小数部分?
最佳答案
假设您只使用字符串:
var str = "4.5 * 5.0 = 22.5 "
// Trim your string in order to remove whitespaces at start and end if there is any.
var trimmedStr = str.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
// Split the string by " " (whitespace)
var splitStr = trimmedStr.componentsSeparatedByString(" ")
// If the split was successful, retrieve the last past (your number result)
var lastPart = ""
if let result = splitStr.last {
lastPart = result
}
// Since it's a XX.X number, split it again by "." (point)
var splitLastPart = lastPart.componentsSeparatedByString(".")
// If the split was successful, retrieve the last past (your number decimal part)
var decimal = ""
if let result = splitLastPart.last {
decimal = result
}
关于ios - 你如何在 swift 中使用解析字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28809298/