Strange behaviour of NSScanner on simple whitespace removal

Posted by Michael Waterfall on Stack Overflow See other posts from Stack Overflow or by Michael Waterfall
Published on 2010-05-13T17:04:49Z Indexed on 2010/05/13 17:34 UTC
Read the original article Hit count: 208

Filed under:
|
|

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?

© Stack Overflow or respective owner

Related posts about iphone

Related posts about objective-c