Re: finding decimals in string
Re: finding decimals in string
- Subject: Re: finding decimals in string
- From: Andrew Merenbach <email@hidden>
- Date: Fri, 24 Aug 2007 13:18:08 -0700
Hi, Daniel,
You may wish to make use of this (caveat emptor: typed in Mail.app):
- (BOOL)stringContainsNumbers:(NSString *)string {
BOOL hasNumbers = NO;
NSCharacterSet *characters = [NSCharacterSet decimalDigitCharacterSet];
NSRange range = [string rangeOfCharactersFromSet:characters];
if (range.location != NSNotFound) {
hasNumbers = YES;
}
return hasNumbers;
}
Cheers,
Andrew
On Aug 24, 2007, at 1:04 PM, Daniel Child wrote:
Hi All,
I have been looking at the NSScanner and NSCharacterSet classes for
a way to find
out whether a string contains digits. I thought something along
these lines might work:
/*********************************************************
FUNCTIONAL METHODS **
* evaluateText
*
* Evaluates whether the textInput field contains numbers and stores
that result
* in the hasNumbers instance variable.
**********************************************************************
*********/
- (void) evaluateText
{
NSCharacterSet *numberChars;
NSScanner *scanner;
NSMutableString *numbersFound;
numberChars = [NSCharacterSet decimalDigitCharacterSet];
scanner = [NSScanner scannerWithString: [self textInput]];
numbersFound = [NSMutableString string];
[scanner scanCharactersFromSet: numberChars intoString:
&numbersFound];
NSLog(@"The character set is %@\n", numberChars);
if ([numbersFound length] == 0) {
NSLog(@"No numbers were found.\n");
[self setHasNumbers: NO];
}
else {
NSLog(@"The numbers found were %@\n", numbersFound);
[self setHasNumbers: YES];
}
}
When I run the debugger, numbersFound gets assigned its memory
space, but no numbers get scanned in. The value of the instance
variable textInput was "one1two2three3", so it should have scanned
in some numbers. My output from the logs is:
2007-08-24 16:02:24.017 CheckForNumbers[1012] Init method went well.
2007-08-24 16:02:24.019 CheckForNumbers[1012] The character set is
<NSBuiltinCharacterSet: 0x306c10>
2007-08-24 16:02:24.019 CheckForNumbers[1012] No numbers were found.
I must be missing something obvious about the way this scanner
function works. I am also wondering if this is the normal approach
to find out whether a string contains certain characters of
interest. Or is there a class I don't know about?
Much thanks.
Daniel
_______________________________________________
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
_______________________________________________
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