简体   繁体   English

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

[英]How do you use parse string in swift?

An issue here to me that if i use parse string for the result of calculator program for instance, 这里有一个问题,如果我使用解析字符串作为计算器程序的结果,例如,

4.5 * 5.0 = 22.5 

how can I use splitting here to depart decimal part from result? 如何在这里使用拆分从结果中删除小数部分?

Use modf to extract decimal part from result. 使用modf从结果中extract decimal part

Objective-C : Objective-C

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

Swift : 斯威夫特

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

Want only interger part from double of float 只需要浮动双倍的整数部分

Want only integer value from double then 只需要double integer数值

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

Want only integer value from float then 只想float integer数值

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

Assuming you're working with strings only : 假设您只使用字符串:

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM