【问题标题】:filter a String with NSScanner and removed white space after numeric character使用 NSScanner 过滤字符串并删除数字字符后的空格
【发布时间】:2012-01-06 13:48:04
【问题描述】:

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

//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,还删除了尾随空格。

有什么提示吗?

【问题讨论】:

  • 您希望收到什么结果?

标签: ios string nsscanner


【解决方案1】:

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

[scanner setCharactersToBeSkipped:nil];

【讨论】:

    猜你喜欢
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-21
    • 2018-12-17
    • 1970-01-01
    • 1970-01-01
    • 2014-08-26
    相关资源
    最近更新 更多