我需要从字符串的开头删除0并在用户输入数字时阻止前导0,我该怎么办?
例如: 用户输入:000090 显示:90
谢谢!
答案 0 :(得分: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"
,则生成的字符串将为空。