且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Swift - 在字符串中搜索并对数字求和

更新时间:2023-02-05 15:04:09

有多种方法可以做到这一点(componentsSeparatedByStringNSScanner、...).这是一个仅使用 Swift 库函数的函数:

There are various method to do that (componentsSeparatedByString, NSScanner, ...). Here is one using only Swift library functions:

let str = "69 - 13"
// split string into components:
let comps = split(str, { $0 == "-" || $0 == " " }, maxSplit: Int.max, allowEmptySlices: false)
// convert strings to numbers (use zero if the conversion fails):
let nums = map(comps) { $0.toInt() ?? 0 }
// compute the sum:
let sum = reduce(nums, 0) { $0 + $1 }
println(sum)