如何从定义如下的字符串中提取数字:
NSString *getNumber = @"Price138.50 Code112.250"
我需要从此字符串中提取138.50
和112.25
。
答案 0 :(得分:5)
使用NSScanner
,稍加修改this Apple example:
NSCharacterSet *numberCharset = [NSCharacterSet characterSetWithCharactersInString:@"0123456789-"];
NSScanner *theScanner = [NSScanner scannerWithString:aString];
while (![theScanner isAtEnd]) {
// Eat non-digits and negative sign
[theScanner scanUpToCharactersFromSet:numberCharset
intoString:NULL];
float aFloat;
if ([theScanner scanFloat:&aFloat]) {
NSLog(@"Found %f", aFloat);
}
}
答案 1 :(得分:-4)
NSString *getNumber = @"Price138.50 Code112.250";
getNumber = [getNumber stringByReplacingOccurrencesOfString:@"Price" withString:@""];
getNumber = [getNumber stringByReplacingOccurrencesOfString:@"Code" withString:@""];
getNumber = [getNumber stringByReplacingOccurrencesOfString:@" " withString:@","];
NSArray *values = [getNumber componentsSeparatedByString:@","];
NSLog(@"Price Value: %@", [values firstObject]);
NSLog(@"Code Value: %@", [values lastObject]);
如果你的字符串是同一种类,那么这可能是一种可能的方式。 不推荐。