1

可能重复:
从字符串中删除前导零

我需要从字符串的开头删除 0 并在用户输入数字时防止前导 0,我该怎么做?

例如:用户输入:000090 显示:90

谢谢!

4

1 回答 1

1

一种方法是使用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];

此时remainder等于@"90"

等效地,可以替换行

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

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

扫描过去所有的零,而不是扫描到第一个非零数字。

这种方法的一个缺点是,如果原始字符串是@"000000000",则结果字符串将为空。

于 2012-11-07T14:36:20.833 回答