NSString is integer?

匆匆过客 提交于 2019-11-26 21:56:07
Stephen Darlington

You could use the -intValue or -integerValue methods. Returns zero if the string doesn't start with an integer, which is a bit of a shame as zero is a valid value for an integer.

A better option might be to use [NSScanner scanInt:] which returns a BOOL indicating whether or not it found a suitable value.

Something like this:

NSScanner* scan = [NSScanner scannerWithString:toCheck]; 
int val; 
return [scan scanInt:&val] && [scan isAtEnd];
coco

Building on an answer from @kevbo, this will check for integers >= 0:

if (fooString.length <= 0 || [fooString rangeOfCharacterFromSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]].location != NSNotFound) {
    NSLog(@"This is not a positive integer");
}

A swift version of the above:

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"
}

Do not forget numbers with decimal point!!!

NSMutableCharacterSet *carSet = [NSMutableCharacterSet characterSetWithCharactersInString:@"0123456789."];
BOOL isNumber = [[subBoldText stringByTrimmingCharactersInSet:carSet] isEqualToString:@""];
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"
}

Update @coco's answer for Swift 5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!