在目标 c 中,我如何检查字符串/NSNumber 是整数还是 int
6 回答
如果您尝试确定 anNSString
是否具有数值,请尝试使用NSNumberFormatter
.
-(BOOL) stringIsNumeric:(NSString *) str {
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
NSNumber *number = [formatter numberFromString:str];
[formatter release];
return !!number; // If the string is not numeric, number will be nil
}
您可以在 NSString 上使用 intValue 方法:
NSString *myString = @"123";
[myString intValue]; // returns (int)123
这是它的 Apple 文档 - 如果它不是有效整数,它将返回 0:http: //developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html #//apple_ref/occ/instm/NSString/intValue
希望有帮助!
I've put this in my category NSString (Util)
.
- (BOOL) isInt {
if ([self isEqualToString:@"0"])
return YES;
return (self.intValue != 0);
}
要检查 NSNumber 是否为整数,请尝试:
const char *t = [(NSNumber *)value objCType];
if (strcmp("i", t) == 0); // YES if integer
For NSString, if you use intValue/integerValue, there are certain cases which are not handled as it takes into consideration only the beginning the string.
For example @"bl3h" was not considered an integer but @" 3h" gave an output of 3
My solution for NSString:
Use :
NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:strName];
NSCharacterSet *numSet = [NSCharacterSet decimalDigitCharacterSet];
if([numSet isSupersetOfSet: charSet])
{
// It is an integer (or it contains only digits)
}
if( [(NSString *)someString intValue] )
{ /* Contains an int fosho! */ }
if( [(NSNumber *)someNumber intValue] )
{ /* Contains an int wich is not 0.... :D */ }
您当然可以首先确定它是 NSString 还是 NSNumber 通过使用
[Object isKindOfClass:[NSString class]] 等等...
– boolValue – charValue – decimalValue – doubleValue – floatValue – intValue – integerValue – longLongValue – longValue – shortValue – unsignedCharValue – unsignedIntegerValue – unsignedIntValue – unsignedLongLongValue – unsignedLongValue – unsignedShortValue
are all methods of NSNumber to get its values. NSString got a few similar ones.