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.
For smaller numbers:
NSString *str = @"000123";
NSString *clean = [NSString stringWithFormat:@"%d", [str intValue]];
For numbers exceeding int32 range:
NSString *str = @"100004378121454";
NSString *clean = [NSString stringWithFormat:@"%d", [str longLongValue]];
This is actually a case that is perfectly suited for regular expressions:
NSString *str = @"00000123";
NSString *cleaned = [str stringByReplacingOccurrencesOfString:@"^0+"
withString:@""
options:NSRegularExpressionSearch
range:NSMakeRange(0, str.length)];
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With