NSString is integer?

前端 未结 5 1934
自闭症患者
自闭症患者 2020-11-28 05:23

How to check if the content of a NSString is an integer value? Is there any readily available way?

There got to be some better way then doing something like this:

相关标签:
5条回答
  • 2020-11-28 05:58

    Do not forget numbers with decimal point!!!

    NSMutableCharacterSet *carSet = [NSMutableCharacterSet characterSetWithCharactersInString:@"0123456789."];
    BOOL isNumber = [[subBoldText stringByTrimmingCharactersInSet:carSet] isEqualToString:@""];
    
    0 讨论(0)
  • 2020-11-28 05:59

    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"
    }
    
    0 讨论(0)
  • 2020-11-28 06:02
    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

    0 讨论(0)
  • 2020-11-28 06:06

    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.

    0 讨论(0)
  • 2020-11-28 06:09

    Something like this:

    NSScanner* scan = [NSScanner scannerWithString:toCheck]; 
    int val; 
    return [scan scanInt:&val] && [scan isAtEnd];
    
    0 讨论(0)
提交回复
热议问题