使用NSScanner过滤String并在数字字符后删除空格

时间:2012-01-06 13:48:05

标签: ios string nsscanner

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

//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);

给了我结果:

  

结果:(A)

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

有任何提示吗?

1 个答案:

答案 0 :(得分:1)

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

[scanner setCharactersToBeSkipped:nil];
相关问题