How to check whether a char is digit or not in Objective-C?

Viewed 17098

I need to check if a char is digit or not.

NSString *strTest=@"Test55";
char c =[strTest characterAtIndex:4];

I need to find out if 'c' is a digit or not. How can I implement this check in Objective-C?

6 Answers

Note: The return value for characterAtIndex: is not a char, but a unichar. So casting like this can be dangerous...

An alternative code would be:

NSString *strTest = @"Test55";
unichar c = [strTest characterAtIndex:4];
NSCharacterSet *numericSet = [NSCharacterSet decimalDigitCharacterSet];
if ([numericSet characterIsMember:c]) {
    NSLog(@"Congrats, it is a number...");
}

In standard C there is a function int isdigit( int ch ); defined in "ctype.h". It will return nonzero (TRUE) if ch is a digit.

Also you can check it manually:

if(c>='0' && c<='9')
{
  //c is digit
}

You may want to check NSCharacterSet class reference.

You can think of writing a generic function like the following for this:

BOOL isNumericI(NSString *s)
{
   NSUInteger len = [s length];
   NSUInteger i;
   BOOL status = NO;

   for(i=0; i < len; i++)
   {
       unichar singlechar = [s characterAtIndex: i];
       if ( (singlechar == ' ') && (!status) )
       {
         continue;
       }
       if ( ( singlechar == '+' ||
              singlechar == '-' ) && (!status) ) { status=YES; continue; }
       if ( ( singlechar >= '0' ) &&
            ( singlechar <= '9' ) )
       {
          status = YES;
       } else {
          return NO;
       }
   }
   return (i == len) && status;
}
Related