12

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.

Monolo
  • 18,205
  • 17
  • 69
  • 103
Muhammed Sadiq.HS
  • 773
  • 1
  • 11
  • 35

5 Answers5

32

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]]; 
Chanchal Raj
  • 4,176
  • 4
  • 39
  • 46
adali
  • 5,977
  • 2
  • 33
  • 40
  • 1
    Hi @adali, but when the string length is >9, it gives some different value.Can you pls check it.For e.g. NSString *str = @"3103282369"; NSString *clean = [NSString stringWithFormat:@"%d", [str intValue]]; NSLog(@"Clean- %@",clean); gives 2147483647 as output. – Muhammed Sadiq.HS May 10 '12 at 13:34
  • oh, because it overflow the range of the int value , ni can change it to longLongValue , then you must format it to %qi instead of %d – adali May 10 '12 at 14:36
  • and if the number is too large you may use the solution below :) – adali May 10 '12 at 14:41
  • the range of int is –2,147,483,648 to 2,147,483,647 and the range of long is –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 , check if it is enough for you – adali May 10 '12 at 14:44
17

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.

Monolo
  • 18,205
  • 17
  • 69
  • 103
1
 - (NSString *) removeLeadingZeros:(NSString *)Instring
 {
        NSString *str2 =Instring ;

        for (int index=0; index<[str2 length]; index++) 
        {
           if([str2 hasPrefix:@"0"]) 
               str2  =[str2 substringFromIndex:1];
            else
                break;
        }
        return str2;

 }
Mudit Bajpai
  • 3,010
  • 19
  • 34
  • Your original code was just missing a return statement before the recursive call to removeLeadingZeros. – Nathan S. May 11 '12 at 05:27
1

The following method also gives the output.

NSString *test = @"0005603235644056";

// Skip leading zeros
NSScanner *scanner = [NSScanner scannerWithString:test];
NSCharacterSet *zeros = [NSCharacterSet
                         characterSetWithCharactersInString:@"0"];
[scanner scanCharactersFromSet:zeros intoString:NULL];

// Get the rest of the string and log it
NSString *result = [test substringFromIndex:[scanner scanLocation]];
NSLog(@"%@ reduced to %@", test, result);
Muhammed Sadiq.HS
  • 773
  • 1
  • 11
  • 35
1

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):

NSString *str = @"000200001111111";
NSString *strippedStr = [NSString stringWithFormat:@"%lld", [temp longLongValue]];

This will give you the result: 200001111111

Otherwise, [NSString stringWithFormat:@"%d", [temp intValue]] will probably return 2147483647 because of overflow.

w3bshark
  • 2,700
  • 1
  • 30
  • 40