Most efficient way to remove leading zeros from Swift 3 string

Jazzmine picture Jazzmine · Nov 6, 2017 · Viewed 8.4k times · Source

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

Answer

vadian picture vadian · Aug 7, 2018

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.