2

I've been trying to filter a string with the following code:

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

which gives me the result:

Result: ( A)

As you can see, it removed not only the number 1 but the trailing space.

Any hints please?

Pedro Sousa
  • 847
  • 1
  • 8
  • 12

1 Answers1

1

I haven't used NSScanner much, but I think your problem here is that by default NSScanner skips whitespace and newlines when it is scanning. Your code will work if you add this line after you instantiate your scanner object:

[scanner setCharactersToBeSkipped:nil];
jonkroll
  • 15,682
  • 4
  • 50
  • 43