Strange behaviour of NSScanner on simple whitespace removal
Asked Answered
R

1

11

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?

Radicel answered 13/5, 2010 at 17:4 Comment(0)
R
23

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

Turns out you just have to set charactersToBeSkipped to nil:

[scanner setCharactersToBeSkipped:nil];
Radicel answered 13/5, 2010 at 17:31 Comment(3)
The documentation doesn't guarantee that nil will work there; it's safer to use an empty NSCharacterSet object instead. One way to create one would be [NSCharacterSet characterSetWithRange:(NSRange){ ' ', 0 }].Eslinger
Looks like nil is fine now according to the documentation . skipSet - The characters to ignore when scanning for a value representation. Pass nil to not ignore any characters.Kaden
Omg thanks, I spent about 2 hours banging my head to the keyboard to see why it's ignoring my spacesDetritus

© 2022 - 2024 — McMap. All rights reserved.