簡體   English   中英

如何以特定方式從 Swift 中的字符串中提取數字

[英]How can I extract numbers from string in Swift in a specific way

我正在努力從 Swift 中的字符串中提取數字。 我正在執行以下操作:

let expression: String = "abc123aa223bb45"
for (indx, ch) in expression.enumerated() {
    if ch.isLetter { continue }
    else if ch.isNumber {
        var val: Int = 0
        while(indx < expression.count && ch.isNumber){
            val = val * 10 + (ch.asciiValue - 48)
            //how can I proceed and increment both indx and ch ...
        }
        // here I'm going to do smthing with every extracted number
    }
}

有人可以幫我完成我遇到的這個問題嗎?

我也使用擴展

extension Character {
    var asciiValue: Int {
        get {
            let s = String(self).unicodeScalars
            return Int(s[s.startIndex].value)
        }
    }
}

正如您在發布的代碼片段中看到的那樣

我正在嘗試編寫一個使用大括號和運算符評估表達式的程序:^,+,-,/,*

但是我遇到了一些問題(我已經用 C++ 和 C# 做過很多次,但我無法用 swift 做到這一點。這真的讓我非常頭疼:)

import Foundation

extension Character {
    var asciiValue: Int {
        get {
            let s = String(self).unicodeScalars
            return Int(s[s.startIndex].value)
        }
    }
}

precedencegroup PowerPrecedence { higherThan: MultiplicationPrecedence }
infix operator ^^ : PowerPrecedence
func ^^ (radix: Double, power: Int) -> Double {
    return (pow(Double(radix), Double(power)))
}

func calc(a: Double, b: Double, o: Character) -> Double {
    switch o {
    case "+":
        return a + b
    case "-":
        return a - b
    case "/":
        return a / b
    case "*":
        return a * b
    case "^":
        return a ^^ Int(b)
    default:
        return 0
    }
}

func nice(o: Character) -> Int {
    if o == "-" || o == "+" { return 1 }
    if o == "*" || o == "/" { return 2 }
    if o == "^" { return 3 }
    return 2020
}

func evaluate(expression: String) -> Double {
    var vals = [Double]()
    var ops = [Character]()

    for (indx, ch) in expression.enumerated() {
        if ch == " " { continue }
        else if ch == "(" { ops.append(ch) }
        else if ch.isNumber {
            var val: Int = 0
            while(indx < expression.count && ch.isNumber){
val = val * 10 + ch.asciiValue - 48 // gives strange error
                //TODO increment indx and ch
            }
            vals.append(Double(val))
        } else if ch == ")" {
            while !ops.isEmpty && ops.last != "(" {
                let val_2: Double = vals.popLast()!
                let val_1: Double = vals.popLast()!
                let op: Character = ops.popLast()!
                vals.append(calc(a: val_1, b: val_2, o: op))
            }
            if !ops.isEmpty { _ = ops.popLast() } // opening brace
        } else {
            while(!ops.isEmpty && nice(o: ops.last!) >= nice(o: ch)){
                let val_2: Double = vals.popLast()!
                let val_1: Double = vals.popLast()!
                let op: Character = ops.popLast()!
                vals.append(calc(a: val_1, b: val_2, o: op))
            }
            ops.append(ch);
        }
    }
    while !ops.isEmpty {
        let val_2: Double = vals.popLast()!
        let val_1: Double = vals.popLast()!
        let op: Character = ops.popLast()!
        vals.append(calc(a: val_1, b: val_2, o: op))
    }
    return vals.last!
}

let exp: String = "2^3+(2+3)"
print(evaluate(expression: exp))

以下代碼片段將從字符串中提取數字

let expression: String = "abc123aa223bb45"    
let stringArray = expression.components(separatedBy: CharacterSet.decimalDigits.inverted)
for item in stringArray {
    if let number = Int(item) {
        print(number)
    }
}

您還可以對具有 function 的 Int 進行擴展

extension Int {
    static func parse(from string: String) -> Int? {
        return Int(string.components(separatedBy: CharacterSet.decimalDigits.inverted).joined())
    }
}

可以這樣使用

let expression: String = "abc123aa223bb45"
if let number = Int.parse(from: expression) {
    print(number)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM