ios - 你如何在 swift 中使用解析字符串?

标签 ios iphone arrays string swift

我遇到的一个问题是,如果我使用解析字符串作为计算器程序的结果,例如,

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/

相关文章:

c++ - 线程安全无锁数组

具有动态可编辑对象和值的 Javascript 数组

ios - 如何将 UIImageView 旋转 20 度?

ios - Xcode 8.3.3 问题调用 String.index(of :)

ios - 更改标签栏的背景颜色

ios - UITableView 不显示标签,也不显示单元格

iphone - 我如何绘制(如在 GLPaint 中)到背景图像上,并使用临时绘图?

php - 在 UTF-8 字符串上使用数组索引时输出错误

ios - 使 UITextField subview 成为 UITableView 中的第一响应者时出错

iphone - cocoa - 我发现了 NSDecimalNumber 的一个错误