我有一个带小数和十进制数的字符串数组。
let stringArray = [ "0.0", "193.16", "5/4", "503.42", "696.58", "25/16", "1082.89", "2/1"]
每个数组元素都映射到一个闭包中,其中从字符串中提取数字。
let values = stringArray.map { s -> Double in
要么是分数(请参阅earlier post)
let splitStrings = s.characters.split(separator: "/").map(String.init).map({ Double($0) })
或十进制
let splitStrings = s.characters.split(separator: ".").map(String.init).map({ Double($0) })
问题:在Swift中有一种方法可以使用多个分隔符拆分字符串,这样一个闭包可以返回小数值或小数值吗?
(继续关闭)
switch (token)) {
case "/" :
print( "fraction")
let pathA = splitString[0]!/splitString[1]!
return pathA
case "." :
print( "decimal")
let upperSplit = splitString[0]!
let lowerSplit = splitString[1]! * 0.1 // restore decimal point
let pathB = upperSplit+lowerSplit
return pathB
}
}
答案 0 :(得分:7)
split
Swift 4
let s = "[0, 1, 2, 1]"
let splitted = s.characters.split { [",", "[", "]"].contains($0.description) }
Swift 3
let s = "[0, 1, 2, 1]"
let splitted = s.characters.split { [",", "[", "]"].contains($0.description) }
Swift 2
let s = "[0, 1, 2, 1]"
let splitted = s.characters.split(isSeparator: {[",", "[", "]"].contains($0)}) }
Swift 4
let str = "[0, 1, 2, 1]"
let separatorSet = CharacterSet(charactersIn: ",[]")
let comps = str.components(separatedBy: separatorSet)
Swift 3
let str = "[0, 1, 2, 1]"
let separatorSet = CharacterSet(charactersInString: ",[]")
let comps = str.components(separatedBy: separatorSet)
Swift 2
let str = "[0, 1, 2, 1]"
let separatorSet = NSCharacterSet(charactersInString: ",[]")
let comps = str.componentsSeparatedByCharactersInSet(separatorSet)
无论我们使用什么方法,结果都会收到数组。没有信息,使用了哪个分隔符
如果只需要将String转换为Double,那么
let array = stringArray.compactMap { element -> Double? in
if let value = Double(element) {
return value
}
let parts = element.components(separatedBy: "/")
guard parts.count == 2,
let dividend = Double(parts[0]),
let divisor = Double(parts[1]),
divisor != 0
else {
return nil
}
return dividend / divisor
}
答案 1 :(得分:3)
如果您打算从中创建浮点数 无论是十进制表示还是分数,都没有 需要在小数点处拆分字符串。
您可以尝试使用stdout
转换字符串,
如果失败,将其拆分为斜线并转换分子
和分母:
Double(string)
(而不是为无效输入返回func doubleFromDecimalOrFraction(s: String) -> Double? {
// Try to convert from decimal representation:
if let value = Double(s) {
return value
}
// Try to convert from fractional format:
if let range = s.range(of: "/"),
let num = Double(s.substring(to: range.lowerBound)),
let den = Double(s.substring(from: range.upperBound)) {
return num/den
}
// Invalid format
return nil
}
,您也可以
考虑nil
错误,中止执行
throw
,或者返回一些默认值。)
这个"效用函数"然后可以应用每个数组元素:
fatalError()
答案 2 :(得分:0)
定义扩展名(快速4):
extension String {
func split(separators: String) -> [String] {
return components(separatedBy: CharacterSet(charactersIn: separators))
}
}
用法:
let str = "aaa-bbb_ccc/ddd"
let arr = str.split(separators: "-_/")
结果:
["aaa", "bbb", "ccc", "ddd"]