Remove leading characters and zero in swift

  • A+
Category:Languages

I tried to remove some characters from string in Swift 4, says: I have

QC00012345, return 12345

QC00009876, return 9876

QC12345678, return 12345678

removing first two characters and those leading zeros.

I looked around in here, people are just using dropFirst then convert String into Int then convert it back to String.

Is there any better way?

 


You could use a regular expression and dropFirst:

let str = "QC00009876" let clean = str.dropFirst(2).replacingOccurrences(of: "^0*", with: "", options: .regularExpression) 

The expression ^0* means "zero or more 0 characters at the start of the string".

Or with just a regular expression:

let str = "QC00009876" let clean = str.replacingOccurrences(of: "^..0*", with: "", options: .regularExpression) 

The expression ^..0* means "any two characters followed by zero or more 0 characters at the start of the string".

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: