-->

NSString by removing the initial zeros?

2020-02-10 05:16发布

问题:

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.

回答1:

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]]; 


回答2:

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.



回答3:

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


回答4:

 - (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;

 }


回答5:

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.