How can I remove leading zeros from an NSString
?
e.g. I have:
NSString *myString;
with values such as @"0002060"
, @"00236"
and @"21456"
.
I want to remove any leading zeros if they occur:
e.g. Convert the previous to @"2060"
, @"236"
and @"21456"
.
Thanks.
This is actually a case that is perfectly suited for regular expressions:
Only one line of code (in a logical sense, line breaks added for clarity) and there are no limits on the number of characters it handles.
A brief explanation of the regular expression pattern:
The
^
means that the pattern should be anchored to the beginning of the string. We need that to ensure it doesn't match legitimate zeroes inside the sequence of digits.The
0+
part means that it should match one or more zeroes.Put together, it matches a sequence of one or more zeroes at the beginning of the string, then replaces that with an empty string - i.e., it deletes the leading zeroes.
The following method also gives the output.
For smaller numbers:
For numbers exceeding int32 range:
In addition to adali's answer, you can do the following if you're worried about the string being too long (i.e. greater than 9 characters):
This will give you the result: 200001111111
Otherwise,
[NSString stringWithFormat:@"%d", [temp intValue]]
will probably return 2147483647 because of overflow.