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

前端 未结 6 1340
一向
一向 2021-02-05 10:46

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

相关标签:
6条回答
  • 2021-02-05 10:49

    There is a C function called isdigit.

    0 讨论(0)
  • 2021-02-05 10:53

    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
    }
    
    0 讨论(0)
  • 2021-02-05 10:54

    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;
    }
    
    0 讨论(0)
  • 2021-02-05 10:59

    You may want to check NSCharacterSet class reference.

    0 讨论(0)
  • 2021-02-05 11:09

    This is actually quite simple:

    isdigit([YOUR_STRING characterAtIndex:YOUR_POS])
    
    0 讨论(0)
  • 2021-02-05 11:13

    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...");
    }
    
    0 讨论(0)
提交回复
热议问题