tags:

views:

407

answers:

5

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

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

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

+1  A: 

There is a C function called isdigit.

zoul
+4  A: 

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
}
werewindle
Thnx alot...I have one question??How to convert the unichar to int?I just tried the followingint ivalue=[[NSNumber numberWithChar:cChar] intValue];Is it correct??
syam
@syam: you do not need to jump through that many hoops. You should be able to convert `unichar` to `int` by doing `int ivalue = cChar;`
dreamlax
Thnx...........
syam
What if they're Japanese numerals '零'-'九'?
amphetamachine
A: 

You may want to check NSCharacterSet class reference.

Eimantas
A: 

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;
}
Kangkan
This function does not do what the OP asked for. Additionally, an `NSScanner` will relieve you of much of the effort your function puts forth.
dreamlax
+1  A: 

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...");
}
Laurent Etiemble