Re: Finding count of a character in a string
Re: Finding count of a character in a string
- Subject: Re: Finding count of a character in a string
- From: Steve Palmer <email@hidden>
- Date: Mon, 22 Aug 2005 06:47:24 -0700
Iterating over the string and calling [characterAtIndex:] might be
sufficient. After all, regardless of the length of the string, any
function that is going to be scanning for an occurrence of a
particular character is going to be working in O(n) time at best. Or
if you know up-front that the string is entirely ASCII, then getting
a pointer to the raw string data with [UTF8String:] and iterating
over it with a pointer might be marginally faster.
If performance really matters then sometimes it can help to look at
the bigger picture (i.e. if you're constructing the string somewhere,
counting the occurrences while the string is being constructed might
be better). How large is a 'large string'?
- Steve
On Aug 22, 2005, at 6:31am, Jim Hamilton wrote:
On Aug 22, 2005, at 4:49 AM, Paul Harvey wrote:
To find out how many of a particular character there was in large
string, I used 'componentsSeparatedByString' method of NSArray
then used [array count] to find out how many there were.
Is there a better way, or is this a typical route?
NSArray *verses = [NSArray alloc];
verses = [chapterText componentsSeparatedByString:@"\n"];
verseCount = [verses count];
Hmm. This would work (aside from an off-by-1 error), but it seems
wasteful; you create an array you don't use, which takes time and
(at least temporarily) space.
You could accomplish the same thing (without that overhead) by
iteratively calling rangeOfString:options:range:. [Or if, as
above, you are looking specifically for line endings, use
getLineStart:end:contentsEnd:forRange:, as it handles any line
ending characters.]
Jim H
--
Jim Hamilton
email@hidden
email@hidden
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
40opencommunity.co.uk
This email sent to email@hidden
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden