NSScanner Skip Additions

Extend NSSscanner's scanUpToString: to skip the separator string.

With test main().

The interface:

/* Created in response to a request on CocoaDev. Pointed out some interesting "gotchas" mentioned in the comments below.
#import <Foundation/Foundation.h> @interface NSScanner(NSScannerSkipAddition) - (BOOL) skipString: (NSString*) prefix; - (BOOL) scanUpToSeparatorAndSkip: (NSString*) separator intoString: (NSString**) resultp; @end

The implementation:

@implementation NSScanner(NSScannerSkipAddition) // if the scanner's location matches prefix, then set the location past the prefix. else return false - (BOOL) skipString: (NSString*) prefix { NSString *string = [self string]; if ([self scanLocation] + [prefix length] <= [string length] && [prefix isEqual: [string substringWithRange: NSMakeRange([self scanLocation], [prefix length])]]) { [self setScanLocation: [self scanLocation] + [prefix length]]; return YES; } return NO; } // like scanUpToString:, but set the location past the prefix - (BOOL) scanUpToSeparatorAndSkip: (NSString*) separator intoString: (NSString**) resultp{ return [self scanUpToString: separator intoString: resultp] && [self skipString: separator]; } @end

And here is the test program to drive it:

int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; NSString *test = @"http://www.apple.com"; NSString *proto; NSString *prefix; NSScanner *scanner = [NSScanner scannerWithString: test]; // fixed: by default will ignore white space [scanner setCharactersToBeSkipped: [[[NSCharacterSet alloc] init] autorelease]]; if([scanner scanUpToSeparatorAndSkip: @"://" intoString: &proto] && [scanner scanUpToSeparatorAndSkip: @"." intoString: &prefix]) { NSLog(@"Hello, World! proto:%@ prefix:%@\n", proto, prefix); } [pool release]; return 0; }
Cocoa Fragments

Page last modified July 4, 2006