Swift - 在字符串中搜索并对数字求和 [英] Swift - Search in string and sum the numbers

查看:59
本文介绍了Swift - 在字符串中搜索并对数字求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我有字符串 "69 - 13" 如何检测字符串中的 "-" 以及如何对字符串 69+13=82 中的数字求和?

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 ?

推荐答案

有多种方法可以做到这一点(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)

这篇关于Swift - 在字符串中搜索并对数字求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆