问题
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 yourstring
value into anInt
compactMap
gets rid of any nil values, ensuring that only valid values are leftreduce
then sums up the values that remain in your array
来源:https://stackoverflow.com/questions/25508398/swift-search-in-string-and-sum-the-numbers