I have a string such as "00123456" that I would like to have in an string "123456", with the leading zeros removed.
I've found several examples for Objective-C but not sure best way to do so with Swift 3.
Thanks
You can do that with Regular Expression
let string = "00123456"
let trimmedString = string.replacingOccurrences(of: "^0+", with: "", options: .regularExpression)
The benefit is no double conversion and no force unwrapping.
Just convert the string to an int and then back to a string again. It will remove the leading zeros.
let numberString = "00123456"
let numberAsInt = Int(numberString)
let backToString = "\(numberAsInt!)"
Result: "123456"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With