Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSString by removing the initial zeros?

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.

like image 852
Muhammed Sadiq.HS Avatar asked May 10 '12 09:05

Muhammed Sadiq.HS


2 Answers

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]]; 
like image 142
adali Avatar answered Oct 01 '22 19:10

adali


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.

like image 30
Monolo Avatar answered Oct 01 '22 19:10

Monolo