swiftsubstringleading-zero

Most efficient way to remove leading zeros from Swift string


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.


Solution

  • 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"