从NSString中提取数字

时间:2016-07-28 16:12:07

标签: cocoa cocoa-touch nsstring

如何从定义如下的字符串中提取数字:

NSString *getNumber = @"Price138.50 Code112.250"

我需要从此字符串中提取138.50112.25

2 个答案:

答案 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]);

如果你的字符串是同一种类,那么这可能是一种可能的方式。 不推荐。