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?
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