NSScanner off-by-one and I can't see why...
NSScanner off-by-one and I can't see why...
- Subject: NSScanner off-by-one and I can't see why...
- From: Graham Cox <email@hidden>
- Date: Thu, 30 Apr 2009 21:45:40 +1000
I'm using a NSScanner to parse a string into a bunch of special keys
for later use. The keys are stored as both the key itself and a
NSRange which indicates its position in the original string. The keys
are parsed as I wish but the ranges are off-by-one except for the
first. I have looped through this code so many times in the debugger
but I just can't see why this is - so I'm now assuming it's a
behaviour of the way NSScanner works that is different from my
expectations somehow.
A typical string to scan would be @"%%city %%state %%country"
The %% symbols are used to flag the presence of a key within the
string (in this case there are only keys plus a couple of spaces in
the string though in practice this could be buried in among other
text). My class returns @"%%" from its +delimiterString method. The
+keyBreakingCharacterSet method returns a character set that includes
a space, among others.
The result for the above string should be keys @"city", @"state",
@country" with ranges {0,6}, {7,7} and {15,9} respectively. The ranges
include the delimiter characters while the keys do not. The results I
actually get are correct keys, but ranges {0,6}, {6,7} and {14,9}. The
spaces don't appear to have been counted, but I'm unclear why that is.
Anyone spot my mistake?
NSScanner* scanner = [NSScanner scannerWithString:[self masterString]];
NSString* key;
NSRange range;
[mKeys removeAllObjects];
while(![scanner isAtEnd])
{
[scanner scanUpToString:[[self class] delimiterString]
intoString:NULL];
if(![scanner isAtEnd])
{
range.location = [scanner scanLocation];
[scanner scanString:[[self class] delimiterString] intoString:NULL];
if([scanner scanUpToCharactersFromSet:[[self class]
keyBreakingCharacterSet] intoString:&key])
{
// if a key was found, find its range and store it
if([key length] > 0)
{
// store the key and its range
range.length = [key length] + [[[self class] delimiterString]
length];
DKTextSubstitutionKey* subsKey = [[DKTextSubstitutionKey alloc]
initWithKey:key range:range];
[mKeys addObject:subsKey];
[subsKey release];
}
}
}
}
tia, Graham
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden