[英]Is value of NSString a NSInteger value in iOS
I am interesting of determine if text in NSString is int value or not. 我对确定NSString中的文本是否为int值很感兴趣。
For example : 例如 :
NSString value = @"something";
int i = value.intValue;
// i -> 0
So i is 0 and it don't give me information if text is real int value. 所以我是0,如果文本是真正的int值,它不会给我信息。
Second problem is if string is int alike : 第二个问题是如果string是int一样的:
NSString vaue = @"10.10.21.32"
int i = value.intValue;
// i -> 10
How to determinate if text is real int value ? 如何确定文本是否为真正的int值?
Marko 马可
Use NSNumberFormatter
, with lenient
set to false and allowsFloats
set to false. 使用NSNumberFormatter
,与lenient
设置为false, allowsFloats
设置为false。
NSNumberFormatter *intFormat = [NSNumberFormatter alloc] init];
intFormat.lenient = false;
intFormat.allowsFloats = false;
NSNumber *myNumber = [intFormat numberFromString:value];
int finalValue;
if (myNumber) { // was able to parse OK
finalValue = [myNumber intValue];
} else {
// handle invalid strings here
}
I did sort of code. 我做了一些代码。 It will use to recognise that string is text, real or int. 它将用来识别字符串是文本,实数还是整数。
#define REGEX_NUMBER @"^[0-9.0-9]*$"
NSString *digitString = @"test";
NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", REGEX_NUMBER];
BOOL isNumber = [phoneTest evaluateWithObject:digitString];
if (isNumber) {
// String contains digit characters
if ([digitString rangeOfString:@"."].location == NSNotFound) {
// String contains real value
int value = [digitString intValue];
} else {
// String contains int value
double value = [digitString doubleValue];
}
} else {
NSLog(@"alpha-numeric value");
// String contains alpha-numeric values.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.