objective-c NSString 是整数吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/565696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 21:09:54  来源:igfitidea点击:

NSString is integer?

objective-ccocoansstring

提问by Carlos Barbosa

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

如何检查 NSString 的内容是否为整数值?有没有现成的方法?

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

必须有一些更好的方法然后做这样的事情:

- (BOOL)isInteger:(NSString *)toCheck {
  if([toCheck intValue] != 0) {
    return true;
  } else if([toCheck isEqualToString:@"0"]) {
    return true;
  } else {
    return false;
  }
}

回答by Stephen Darlington

You could use the -intValueor -integerValuemethods. 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.

您可以使用-intValueor-integerValue方法。如果字符串不是以整数开头,则返回零,这有点遗憾,因为零是整数的有效值。

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

更好的选择可能是使用[NSScanner scanInt:]which 返回一个BOOL指示它是否找到合适的值。

回答by Steven Green

Something like this:

像这样的东西:

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

回答by coco

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

基于@kevbo的回答,这将检查整数 >= 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"
}

回答by TtheTank

Do not forget numbers with decimal point!!!

不要忘记带小数点的数字!!!

NSMutableCharacterSet *carSet = [NSMutableCharacterSet characterSetWithCharactersInString:@"0123456789."];
BOOL isNumber = [[subBoldText stringByTrimmingCharactersInSet:carSet] isEqualToString:@""];

回答by black_pearl

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

更新@coco 对 Swift 5 的回答