remove leading 0 from a string, objective C [duplicate]

耗尽温柔 提交于 2019-12-11 04:19:47

问题


Possible Duplicate:
Removing leading zeroes from a string

I need to remove 0 from the beginning of a string and prevent leading 0s when user input the number, how can I do it?

For example: user input: 000090 display: 90

Thanks!


回答1:


One approach is to use an NSScanner:

NSString *string = @"000090";
NSCharacterSet *nonzeroNumberCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@"123456789"];
NSScanner *scanner = [NSScanner scannerWithString:string];
[scanner scanUpToCharactersFromSet:nonzeroNumberCharacterSet intoString:nil];
NSString *remainder = nil;
NSCharacterSet *emptyCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@""];
[scanner scanUpToCharactersFromSet:emptyCharacterSet intoString:&remainder];

At this point remainder is equal to @"90".

Equivalently, one could replace the lines

NSCharacterSet *nonzeroNumberCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@"123456789"];
NSScanner *scanner = [NSScanner scannerWithString:string];

with

NSCharacterSet *zeroNumberCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@"0"];
[scanner scanCharactersFromSet:zeroNumberCharacterSet intoString:nil];

to scan past all the zeros rather than to scan until the first non-zero number.

One drawback of this approach is that if the original string is @"000000000", the resulting string will be empty.



来源:https://stackoverflow.com/questions/13271612/remove-leading-0-from-a-string-objective-c

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