15

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

Jazzmine
  • 1,837
  • 8
  • 36
  • 54

4 Answers4

43

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.

vadian
  • 274,689
  • 30
  • 353
  • 361
18

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"

livtay
  • 553
  • 4
  • 9
  • 2
    Be careful here with the forced unwrap: make sure that the String is not empty ("") i.e. with a guard statement. Otherwise this code will crash. – Blackvenom Mar 06 '18 at 11:41
  • In this case the string is defined so it will never be nil. But yes, if the string is dynamic you would have to handle it to guard for a nil value. – livtay Mar 06 '18 at 14:01
  • 2
    if the resulting number is too big this will fail. – jimijon Dec 17 '18 at 13:36
  • 2
    why is this marked correct, it's obviously not the right type safe decision. – Schemetrical Jul 27 '19 at 00:47
  • Be careful with this implementation. I used it for a production code and it crushed because some user entered a number that exceeds the Int64 limit. `Int(numberString)` was nil in this case, and force-unwrapping caused a crash – Roma Kavinskyi May 13 '22 at 03:53
1

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)
}
tBug
  • 789
  • 9
  • 13
-1
let number = "\(String(describing: Int(text)!))"
nikdange_me
  • 2,949
  • 2
  • 16
  • 24
  • 1
    Why not simply `"\(Int(text)!)"` or `String(Int(text)!)`? Creating a string from a string with String Interpolation is redundant. – vadian Aug 20 '18 at 07:20