Re: Newbie Question: Find spaces inside a string
Re: Newbie Question: Find spaces inside a string
- Subject: Re: Newbie Question: Find spaces inside a string
- From: Ricky Sharp <email@hidden>
- Date: Wed, 26 Oct 2005 19:11:36 -0500
On Oct 26, 2005, at 1:10 PM, Douglas Davidson wrote:
On Oct 25, 2005, at 9:10 PM, Julian Sanchez wrote:
However, I tried to be a bit smart here and provide additional
functionality in which if a user enters a sentence (with its
corresponding spaces) I would like to find that out and count only
the letters.
First thing that came to mind was to write a loop that would use
NSString:characterAtIndex, traversing the string one character at
a time.
My question is: Surely there's a better (and quicker) way to do
this, isn't it? What way is that?
There are quite a few possibilities other than simply spaces and
letters. If you can figure out what sets of characters you are
actually interested in, you should be able to construct something
fairly simply using e.g. -[NSString
rangeOfCharacterFromSet:options:range:], or NSScanner's character
set methods.
If you are interested in counting words, you could use e.g. -
[NSAttributedString nextWordFromIndex:forward:], which is what is
used for option-arrowing. There is also -[NSSpellChecker
countWordsInString:language:], which may be more linguistically
sensitive, but you must have a fallback ready in case the current
spellchecker does not support word count and so returns -1.
I recently coded the following to normalize a name (trim whitespace
from both ends as well as to replace runs of internal whitespace with
a single space):
- (NSString*)normalizedName:(NSString*)aName
{
NSCharacterSet* theCharacterSet = [NSCharacterSet
whitespaceAndNewlineCharacterSet];
NSString* theName = [aName
stringByTrimmingCharactersInSet:theCharacterSet];
NSMutableString* theNormalizedName = [NSMutableString string];
NSScanner* theScanner = [NSScanner
scannerWithString:theName];
NSString* theNameComponent = nil;
do
{
if ([theScanner scanUpToCharactersFromSet:theCharacterSet
intoString:&theNameComponent])
{
[theNormalizedName appendString:theNameComponent];
[theNormalizedName appendString:@" "];
}
}
while (![theScanner isAtEnd]);
return [theNormalizedName
stringByTrimmingCharactersInSet:theCharacterSet];
}
I'll have to check out nextWordFromIndex:forward: and see if it will
provide for an easier implementation.
___________________________________________________________
Ricky A. Sharp mailto:email@hidden
Instant Interactive(tm) http://www.instantinteractive.com
_______________________________________________
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