Possible Duplicate:
Removing leading zeroes from a string
I need to remove leading 0s in an NSString
, a quick way I can think of is to convert the string to an NSNumber
then convert back to NSString
which will give me the clean string, although I'm not sure if it works. Is there any other way to do this?
Thanks
This works, I've tested it. And I think this is a very good way. Less code less bug. KISS.
So just for fun, I decided to time the various ways of doing this. This was by no means a scientific test, done mostly for my amusement, but some of you might like to see it anyway.
I created a method and substituted the various routines to process strings representing the numbers 0 - 100,000 all with three leading 0's.
Keep in mind however, that even the slowest method is going to be perfectly acceptable if you only have one (or even one hundred) of these strings to trim. (Using the number formatter takes about .000012039905 seconds, or about 1/100th of a millisecond.) Other things such as how easy your code is to read and understand is usually more important unless you really do need to process a large file full of strings like this. My personal favorite is still the regular expression, because it is relatively fast and immediately obvious what you are trying to accomplish, even without documentation.
Here are the results (from fastest to slowest):
Looping through the string
Converting to an int and then back to a NSString
Using a NSScanner
Using a regular expression
Using a static number formatter
Using a number formatter
You could use regular expressions.
If you doing it a lot (as in thousands of times) you may benefit from using a compiled
NSRegularExpression
.