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
There is a C function called isdigit.
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 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;
}
You may want to check NSCharacterSet
class reference.
This is actually quite simple:
isdigit([YOUR_STRING characterAtIndex:YOUR_POS])
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...");
}