字符串转换为Int并将逗号替换为加号

编程入门 行业动态 更新时间:2024-10-12 01:30:04
本文介绍了字符串转换为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...

请帮忙! 谢谢

Please Help! Thanks

推荐答案

  • 使用组件(separatedBy:)分解以逗号分隔的字符串。
  • 使用 trimmingCharacters(in:)删除之前的空格在每个元素之后
  • 使用 Int()将每个元素转换为整数。
  • 使用 flatMap 删除任何无法转换为 Int 的项目。
  • 使用 reduce 来总结 Int 的数组。

  • Use components(separatedBy:) to break up the comma-separated string.
  • Use trimmingCharacters(in:) to remove spaces before and after each element
  • Use Int() to convert each element into an integer.
  • Use flatMap to remove any items that couldn't be converted to Int.
  • Use reduce to sum up the array of Int. let input = " 98 ,99 , 97, 96 " let values = inputponents(separatedBy: ",").flatMap { Int($0.trimmingCharacters(in: .whitespaces)) } let sum = values.reduce(0, +) print(sum) // 390

  • 更多推荐

    字符串转换为Int并将逗号替换为加号

    本文发布于:2023-07-14 20:10:25,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1106734.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:加号   并将   逗号   转换为   字符串

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!