1

我一直在尝试使用以下代码过滤字符串:

//the String with the original text  
NSString *unfilteredString = @"( A1 )";  
//initialize a string that will hold the result  
NSMutableString *resultString = [NSMutableString stringWithCapacity:unfilteredString.length];  

NSScanner *scanner = [NSScanner scannerWithString:unfilteredString];  
NSCharacterSet *allowedChars = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];  

while ([scanner isAtEnd] == NO) {  
    NSString *buffer;  
    if ([scanner scanCharactersFromSet:allowedChars intoString:&buffer]) {  
        [resultString appendString:buffer];       
    } 
    else {  
        [scanner setScanLocation:([scanner scanLocation] + 1)];  
    }  
}  
NSLog (@"Result: %@", resultString);

这给了我结果:

结果:(一)

如您所见,它不仅删除了数字 1,还删除了尾随空格。

请问有什么提示吗?

4

1 回答 1

1

我没有太多使用 NSScanner,但我认为您的问题是默认情况下 NSScanner 在扫描时会跳过空格和换行符。如果在实例化扫描仪对象后添加此行,您的代码将起作用:

[scanner setCharactersToBeSkipped:nil];
于 2012-01-06T22:50:07.407 回答