【问题标题】:How do you use parse string in swift?你如何在swift中使用解析字符串?
【发布时间】:2015-03-02 12:00:21
【问题描述】:

这里有个问题,例如,如果我使用解析字符串作为计算器程序的结果,

4.5 * 5.0 = 22.5 

如何在此处使用拆分来将小数部分与结果分开?

【问题讨论】:

  • 我的意思是如果结果是 22.0 ,我只想要 22 而不是 22.0,当然如果它是 22.5 ,0.5 将作为 22.5 存在,但是 0 of 22.0 的结果是 22.0 或什么时候键入数字 22.0 而不是 22 不应该在点的右侧?

标签: ios iphone arrays string swift


【解决方案1】:

假设您只使用字符串:

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
}

【讨论】:

  • 您应该使用if let 语法:if let result = splitStr.last { lastPart = result },而不是使用count 后跟last! 的测试。 ! 很危险,只有在没有实际替代方案时才应使用。
  • NP。另外,查看类似于componentsSeparatedByStringSwift.splitif let result = last(split(str) { $0 == " " }), let decimal = last(split(result) {$0 == "."}) { println(decimal) }
【解决方案2】:

从结果中使用modfextract decimal part

Objective-C

double integral = 22.5;
double fractional = modf(integral, &integral);
NSLog(@"%f",fractional);

斯威夫特

 var integral:Double  = 22.5;
 let fractional:Double = modf(integral,&integral);
 println(fractional);

只想要浮点数的整数部分

然后只想要来自doubleinteger

 let integerValue:Int = Int(integral)
 println(integerValue)

然后只想要来自floatinteger

 let integerValue:Float = Float(integral)
 println(integerValue)

【讨论】:

  • 我的意思是如果结果是 22.0 ,我只想要 22 而不是 22.0,当然如果它是 22.5 ,0.5 将作为 22.5 存在,但是 0 of 22.0 的结果是 22.0 或什么时候键入数字 22.0 而不是 22 不应该在点的右侧?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-24
相关资源
最近更新 更多