目标 c:检查是否是整数/整数/数字
在 Objective C 中,我如何检查字符串/NSNumber 是整数还是 int
In objective c, how can i check if a string/NSNumber is an integer or int
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果您尝试确定
NSString
是否具有数值,请尝试使用NSNumberFormatter
。If you're trying to determine whether or not an
NSString
has a numeric value or not, try usingNSNumberFormatter
.您可以在 NSString 上使用 intValue 方法:
这是 Apple 文档 - 如果它不是有效整数,它将返回 0: http://developer.apple.com/mac/library/documentation/Cocoa /Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/intValue
希望有帮助!
You can use the intValue method on NSString:
Here is the Apple documentation for it - it will return 0 if it's not a valid integer: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/intValue
Hope that helps!
我已将其放入我的类别
NSString (Util)
中。I've put this in my category
NSString (Util)
.要检查 NSNumber 是否为整数,请尝试:
To check if a NSNumber if an integer try:
对于 NSString,如果您使用 intValue/integerValue,则某些情况不会被处理,因为它只考虑字符串的开头。
例如 @"bl3h" 不被视为整数,但 @"3h" 给出的输出为 3
我的 NSString 解决方案:
使用:
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 :
来确定它是 NSString 还是 NSNumber
当然,您可以首先使用[Object isKindOfClass:[NSString class]] 等
... – boolValue
– 字符值
– 小数值
– 双值
– 浮点值
– intValue
– 整数值
– longLongValue
– 长值
– 短值
– unsignedCharValue
– 无符号整数值
– 无符号整数值
– unsignedLongLongValue
– 无符号长值
– unsignedShortValue
都是 NSNumber 获取其值的方法。
NSString 有一些类似的。
You can ofcourse first determine whether its a NSString or NSNumber by using
[Object isKindOfClass:[NSString class]] etc...
– 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.