【问题标题】:String convert to Int and replace comma to Plus sign字符串转换为 Int 并将逗号替换为加号
【发布时间】:2017-02-25 03:11:47
【问题描述】:

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

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

请帮忙! 谢谢

【问题讨论】:

    标签: swift string int swift3


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

      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
      

    【讨论】:

      【解决方案2】:

      适用于 Swift 3Swift 4

      简单方法:硬编码。仅当您知道即将出现的整数的确切数量、想要进一步计算和打印/使用时才有用。

      let string98: String = "98"
      let string99: String = "99"
      let string100: String = "100"
      let string101: String = "101"
      
      let int98: Int = Int(string98)!
      let int99: Int = Int(string99)!
      let int100: Int = Int(string100)!
      let int101: Int = Int(string101)!
      
      // optional chaining (if or guard) instead of "!" recommended. therefore option b is better
      
      let finalInt: Int = int98 + int99 + int100 + int101
      

      print(finalInt) // prints Optional(398) (optional)

      花式方式作为函数:通用方式。最后,您可以在此处放入任意数量的字符串。例如,您可以先收集所有字符串,然后使用数组计算它们。

      func getCalculatedIntegerFrom(strings: [String]) -> Int {
      
          var result = Int()
      
          for element in strings {
      
              guard let int = Int(element) else {
                  break // or return nil
                  // break instead of return, returns Integer of all 
                  // the values it was able to turn into Integer
                  // so even if there is a String f.e. "123S", it would
                  // still return an Integer instead of nil
                  // if you want to use return, you have to set "-> Int?" as optional
              }
      
              result = result + int
      
          }
      
          return result
      
      }
      
      let arrayOfStrings = ["98", "99", "100", "101"]
      
      let result = getCalculatedIntegerFrom(strings: arrayOfStrings)
      

      print(result) // prints 398 (non-optional)

      【讨论】:

        【解决方案3】:

        let myString = "556" let myInt = Int(myString)

        【讨论】:

        • 这与我的回答有何不同?
        猜你喜欢
        • 2018-08-16
        • 2022-01-22
        • 2019-12-26
        • 1970-01-01
        • 1970-01-01
        • 2013-10-23
        • 1970-01-01
        • 2012-02-03
        • 1970-01-01
        相关资源
        最近更新 更多