Swift - Search in string and sum the numbers

天大地大妈咪最大 提交于 2019-12-12 05:34:05

问题


Hey guys I have string "69 - 13" How to detect "-" in the string and how to sum the numbers in the string 69+13=82 ?


回答1:


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)



回答2:


Here is an updated implementation in Swift 4 that relies on higher order functions to perform the operation:

let string = "69+13"
let number = string.components(separatedBy: CharacterSet.decimalDigits.inverted)
     .compactMap({ Int($0) })
     .reduce(0, +)
print(number) // 82
  • The components(separatedBy: CharacterSet.decimalDigits.inverted) removes all non-digit values and creates an array for each group of values (in this case 69 and 13)
  • Int($0) converts your string value into an Int

  • compactMap gets rid of any nil values, ensuring that only valid values are left

  • reduce then sums up the values that remain in your array



来源:https://stackoverflow.com/questions/25508398/swift-search-in-string-and-sum-the-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!