NSString is integer?
如果一个NSSTRING的含量是一个整合值,怎么检查?是否有任何实际可行的方式?
有人会做一些更好的事情
1 2 3 4 5 6 7 8 9 | - (BOOL)isInteger:(NSString *)toCheck { if([toCheck intValue] != 0) { return true; } else if([toCheck isEqualToString:@"0"]) { return true; } else { return false; } } |
您可以使用
更好的选择可能是使用
像这样:
1 2 3 | NSScanner* scan = [NSScanner scannerWithString:toCheck]; int val; return [scan scanInt:&val] && [scan isAtEnd]; |
基于@kevbo的答案,这将检查大于等于0的整数:
1 2 3 | if (fooString.length <= 0 || [fooString rangeOfCharacterFromSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]].location != NSNotFound) { NSLog(@"This is not a positive integer"); } |
上述的快速版本:
1 2 3 4 5 6 | func getPositive(incoming: String) -> String { if (incoming.characters.count <= 0) || (incoming.rangeOfCharacterFromSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet) != nil) { return"This is NOT a positive integer" } return"YES! +ve integer" } |
不要忘记带小数点的数字!!!!
1 2 | NSMutableCharacterSet *carSet = [NSMutableCharacterSet characterSetWithCharactersInString:@"0123456789."]; BOOL isNumber = [[subBoldText stringByTrimmingCharactersInSet:carSet] isEqualToString:@""]; |
1 2 3 4 5 6 | func getPositive(input: String) -> String { if (input.count <= 0) || (input.rangeOfCharacter(from: NSCharacterSet.decimalDigits.inverted) != nil) { return"This is NOT a positive integer" } return"YES! integer" } |
更新@coco对swift 5的回答