2012-11-07 59 views

回答

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 *zeroNumberCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@"0"]; 
[scanner scanCharactersFromSet:zeroNumberCharacterSet intoString:nil]; 

掃描過去所有的零,而不是掃描,直到第一個非零數字代替線

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

此方法的一個缺點是,如果原始字符串爲@"000000000",則生成的字符串將爲空。