NSString by removing the initial zeros?

自闭症网瘾萝莉.ら 提交于 2019-11-29 03:53:26
adali

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.

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

 }

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!