RE: counting characters
RE: counting characters
- Subject: RE: counting characters
- From: "Jonathan E. Jackel" <email@hidden>
- Date: Thu, 15 Apr 2004 11:52:17 -0400
>
To count the occurance of characters or a group of characters in an
>
NSString, I now use a for loop, and compare each character with an
>
NSCharacterSet. It works fine, but I was wondering if I can do this
>
easier/more efficiently using an NSScanner.
>
The most compact code for counting characters that I can come up with is:
unsigned occurrences = [[[targetString mutableCopy] autorelease]
replaceOccurrencesOfString:searchString withString:searchString
options:NSLiteralSearch range:NSMakeRange(0,[targetString length])];
but this only works in 10.2 and later, and it is not especially speedy.
Scanners are pretty easy to use for this purpose. You'll need to alternate
calls of -scanUpToString:intoString: with -scanString:intoString:. The
former searches from the scan location until it gets a hit or reaches the
end of the scanner's string. The latter moves the scan location past that
hit so that the scanner can search for the next hit.
By default a scanner skips whitespace and newline characters. If there's
any chance you'll be searching for those characters, you'll need to
setCharactersToBeSkipped:nil.
int occurrences = 0;
NSScanner scanner = [NSScanner scannerWithString:theString];
[scanner setCharactersToBeSkipped:nil];
while(![scanner isAtEnd])
{
if([scanner scanUpToString:searchString intoString:nil]) occurrences++;
[scanner scanString:searchString intoString:nil];
}
Jonathan
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.