Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to remove leading zeros from Swift 3 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 3.

Thanks

like image 721
Jazzmine Avatar asked Nov 06 '17 19:11

Jazzmine


2 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.

like image 157
vadian Avatar answered Oct 16 '22 05:10

vadian


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"

like image 17
livtay Avatar answered Oct 16 '22 05:10

livtay