• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
RE: counting characters
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

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.


  • Follow-Ups:
    • Re: counting characters
      • From: Allan Odgaard <email@hidden>
References: 
 >counting characters (From: Koen van der Drift <email@hidden>)

  • Prev by Date: Responding from a delegate?
  • Next by Date: Re: Associating a library created file with my application
  • Previous by thread: Re: counting characters
  • Next by thread: Re: counting characters
  • Index(es):
    • Date
    • Thread