Question

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?

Was it helpful?

Solution

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];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top