String convert to Int and replace comma to Plus sign

喜夏-厌秋 提交于 2020-01-09 07:12:10

问题


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:

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

Please Help! Thanks


回答1:


  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
    



回答2:


For Swift 3 and Swift 4.

Simple way: Hard coded. Only useful if you know the exact amount of integers coming up, wanting to get calculated and printed/used further on.

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)

Fancy way as a function: Generic way. Here you can put as many strings in as you need in the end. You could, for example, gather all the strings first and then use the array to have them calculated.

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)



来源:https://stackoverflow.com/questions/40064294/string-convert-to-int-and-replace-comma-to-plus-sign

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!