字符串转换为 Int 并将逗号替换为加号 [英] String convert to Int and replace comma to Plus sign

查看:20
本文介绍了字符串转换为 Int 并将逗号替换为加号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Swift,我尝试获取在应用程序的文本视图中输入的数字列表,并通过提取成绩计算器的每个数字来创建此列表的总和.此外,用户输入的值的数量每次都会改变.一个例子如下所示:

Using Swift, I'm trying to take a list of numbers input in a text view in an app and create a sum of this list by extracting each number for a grade calculator. Also the amount of values put in by the user changes each time. An example is shown below:

字符串:98,99,97,96...试图得到:98+99+97+96...

String of: 98,99,97,96... Trying to get: 98+99+97+96...

请帮忙!谢谢

推荐答案

  1. 使用 components(separatedBy:) 拆分逗号分隔的字符串.
  2. 使用trimmingCharacters(in:)去除每个元素前后的空格
  3. 使用 Int() 将每个元素转换为整数.
  4. 使用 compactMap(以前称为 flatMap)删除任何无法转换为 Int 的项目.
  5. 使用reduceInt的数组求和.

  1. Use components(separatedBy:) to break up the comma-separated string.
  2. Use trimmingCharacters(in:) to remove spaces before and after each element
  3. Use Int() to convert each element into an integer.
  4. Use compactMap (previously called flatMap) to remove any items that couldn't be converted to Int.
  5. Use reduce to sum up the array of Int.

let input = " 98 ,99 , 97, 96 "

let values = input.components(separatedBy: ",").compactMap { Int($0.trimmingCharacters(in: .whitespaces)) }
let sum = values.reduce(0, +)
print(sum)  // 390

这篇关于字符串转换为 Int 并将逗号替换为加号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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