从字符串中删除前导0,目标C.

时间:2012-11-07 14:20:29

标签: objective-c nsstring

  

可能重复:
  Removing leading zeroes from a string

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

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

谢谢!

1 个答案:

答案 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",则生成的字符串将为空。