NSScanner Skip Additions
Extend NSSscanner's scanUpToString: to skip the separator string.
With test main().
The interface:
#import <Foundation/Foundation.h>
@interface NSScanner(NSScannerSkipAddition)
- (BOOL) skipString: (NSString*) prefix;
- (BOOL) scanUpToSeparatorAndSkip: (NSString*) separator intoString: (NSString**) resultp;
@end
The implementation:
@implementation NSScanner(NSScannerSkipAddition)
//
- (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;
}
//
- (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];
//
[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;
}
Page last modified July 4, 2006