Hamza
Hamza

Reputation: 251

Extract value from a string in swift

I have a string "25% off", i want to extract only value 25 from this, how can i extract it in swift, previously i had done with objective c but in swift hoe can we do that? I have tried this code but failed,

 let discount = UserDefaults.standard.string(forKey: "discount")
    print(discount)
    let index = discount?.index((discount?.startIndex)!, offsetBy: 5)
    discount?.substring(to: index!)
    print(index)

How can i get 25 from it?

Upvotes: 0

Views: 1926

Answers (2)

CodeBender
CodeBender

Reputation: 36612

You can use a numeric character set to just extract the number from that string:

let discount = "25% off"
let number = discount.components(separatedBy: 
             CharacterSet.decimalDigits.inverted).joined(separator: "") 
print(number) // 25

Just be sure to use the inverted var, otherwise you will get the non-numbers.

Upvotes: 0

vadian
vadian

Reputation: 285059

A smart solution is to find the range of all consecutive digits from the beginning of the string with Regular Expression, the index way is not very reliable.

let discount = "25% off"
if let range = discount.range(of: "^\\d+", options: .regularExpression) {
    let discountValue = discount[range]
    print(discountValue)
}

You can even search for the value including the percent sign with pattern "^\\d+%"

Upvotes: 1

Related Questions