Most efficient way to remove leading zeros from Swift 3 string

Viewed 11424

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

4 Answers

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"

First, create Validator then use it in any class. This is an example and it works :) This is swift 4.0

class PhoneNumberExcludeZeroValidator {
    func validate(_ value: String) -> String {
        var subscriberNumber = value
        let prefixCase = "0"
        if subscriberNumber.hasPrefix(prefixCase) {
            subscriberNumber.remove(at: subscriberNumber.startIndex)
        }
        return subscriberNumber
    }
}

example for usage:

if let countryCallingCode = countryCallingCodeTextField.text, var subscriberNumber = phoneNumberTextField.text {

     subscriberNumber = PhoneNumberExcludeZeroValidator().validate(subscriberNumber)

          let phoneNumber = "\(countryCallingCode)\(subscriberNumber)"
          registerUserWith(phoneNumber: phoneNumber)
}
let number = "\(String(describing: Int(text)!))"
Related