我得到的值是这样的264.8,我想在点之前和之后取值。我可以在这个点之前取值
var string = "264.8"
var index = string2.rangeOfString(".", options: .BackwardsSearch)?.startIndex
var substring = string.substringToIndex(index2!)
但请问我怎么能在点之后拿走它?
答案 0 :(得分:3)
试试这段代码:
var string = "264.8"
var numbers = string.componentsSeparatedByString(".")
print(numbers[0])
print(numbers[1])
答案 1 :(得分:2)
var string = "264.8"
let partsArr = string.componentsSeparatedByString(".")
var beforeDot: String = partsArr[0]
var afterDot: String? = partsArr[1]
答案 2 :(得分:1)
为了完整起见,另一种方法是使用split
:
let string = "264.8"
let result = string.characters.split(".").map { String($0) }
print(result[0]) // "264"
print(result[1]) // "8"
另一个是使用componentsSeparatedByCharactersInSet
:
let string = "264.8"
let result = string.componentsSeparatedByCharactersInSet(NSCharacterSet.punctuationCharacterSet())
print(result[0]) // "264"
print(result[1]) // "8"
答案 3 :(得分:0)
或者,定义一个用于处理转换的闭包变量
let mySubstringClosure : (String) -> (String) = { $0.componentsSeparatedByString(".").first ?? $0 }
let substring1 = mySubstringClosure("264.8") // "264"
let substring2 = mySubstringClosure("264") // "264"
let substring3 = mySubstringClosure("") // ""
请注意,即使字符串中不存在点.
,或者字符串为空,此代码也会安全运行。