Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange behaviour of NSScanner on simple whitespace removal

I'm trying to replace all multiple whitespace in some text with a single space. This should be a very simple task, however for some reason it's returning a different result than expected. I've read the docs on the NSScanner and it seems like it's not working properly!

NSScanner *scanner = [[NSScanner alloc] initWithString:@"This    is   a test of NSScanner   !"];
NSMutableString *result = [[NSMutableString alloc] init];
NSString *temp;
NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
while (![scanner isAtEnd]) {

    // Scan upto and stop before any whitespace
    [scanner scanUpToCharactersFromSet:whitespace intoString:&temp];

    // Add all non whotespace characters to string
    [result appendString:temp];

    // Scan past all whitespace and replace with a single space
    if ([scanner scanCharactersFromSet:whitespace intoString:NULL]) {
        [result appendString:@" "];
    }

}

But for some reason the result is @"ThisisatestofNSScanner!" instead of @"This is a test of NSScanner !".

If you read through the comments and what each line should achieve it seems simple enough!? scanUpToCharactersFromSet should stop the scanner just as it encounters whitespace. scanCharactersFromSet should then progress the scanner past the whitespace up to the non-whitespace characters. And then the loop continues to the end.

What am I missing or not understanding?

like image 945
Michael Waterfall Avatar asked May 13 '10 17:05

Michael Waterfall


1 Answers

Ah, I figured it out! By default the NSScanner skips whitespace!

Turns out you just have to set charactersToBeSkipped to nil:

[scanner setCharactersToBeSkipped:nil];
like image 69
Michael Waterfall Avatar answered Oct 07 '22 16:10

Michael Waterfall