ObjectiveC: NSScanner scanDouble problem
In my iPhone app I am trying to understand if a string is a valid number or not, the code below works most of the time but when I have a value starting with number and ends with text it wrongly returns "true" e.g "34rty"
if([[NSSc开发者_如何学运维anner scannerWithString:value] scanDouble:NULL] ){
val=[NSNumber numberWithDouble:[value doubleValue]];
}
what is wrong here?
scanDouble
return via a reference.
NSString *string = @"34rty";
NSScanner *scanner = [NSScanner scannerWithString:string];
double doubleValue;
[scanner scanDouble:&doubleValue];
NSNumber *doubleNumber = [NSNumber numberWithDouble:doubleValue];
NSLog(@"doubleValue: %f", doubleValue);
NSLog(@"doubleNumber: %@", doubleNumber);
NSLog output:
doubleValue: 34.000000
doubleNumber: 34
You will have to scan up to the number if there is preceding text.
As @Benjamin says, a RegEx may be a better option for just checking.
NSScanner stops at the first matching character. So it finds '3', returns positive as it did scan a double, and then stops running. It doesn't check every character.
A REGEX check is a better choice for this purpose.
精彩评论