我需要检查一个字符是否是数字。
NSString *strTest=@"Test55";
char c =[strTest characterAtIndex:4];
我需要找出'C'是否为数字。 我该如何在Objective-C中实现此检查?
我需要检查一个字符是否是数字。
NSString *strTest=@"Test55";
char c =[strTest characterAtIndex:4];
我需要找出'C'是否为数字。 我该如何在Objective-C中实现此检查?
注意: characterAtIndex:
的返回值不是char
,而是unichar
。因此像这样进行强制类型转换可能存在危险...
另一个可选代码如下:
NSString *strTest = @"Test55";
unichar c = [strTest characterAtIndex:4];
NSCharacterSet *numericSet = [NSCharacterSet decimalDigitCharacterSet];
if ([numericSet characterIsMember:c]) {
NSLog(@"Congrats, it is a number...");
}
在标准C语言中,有一个名为int isdigit( int ch );
的函数被定义在"ctype.h"头文件中。如果ch是数字,则该函数将返回非零值(TRUE)。
您也可以手动检查:
if(c>='0' && c<='9')
{
//c is digit
}
isdigit()
可能更好,因为它更易于阅读...尽管使用该函数可能掩盖了它无法处理非ASCII数字字符的事实。 - ArtOfWarfareisdigit([YOUR_STRING characterAtIndex:YOUR_POS])
decimalDigitCharacterSet
解决方案。https://dev59.com/nHE95IYBdhLWcg3wi-Uc#2271360 - ArtOfWarfare您可能需要查看NSCharacterSet
类的参考文档。
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;
}
NSScanner
可以减轻您的函数所需付出的大部分工作。 - dreamlax
characterAtIndex:
返回的是unichar
而不是char
。如果你处理非 ASCII 文本可能会导致误判。请注意截断。 - dreamlax