如何从NSString中提取数字?

时间:2012-11-13 06:59:25

标签: ios nsstring

我有一个NSString数据,其格式如下:

10mm x 1000mm  
4mm x 20mm  
50mm x 200mm  
250mm x 2000mm  

有人可以建议如何在每种情况下提取两个单独的数字吗?

  

10和1000
  4和20
  50和200
  250和2000

等等。

3 个答案:

答案 0 :(得分:2)

如果格式,请始终

number, "mm x ", number, "mm"

然后您可以使用NSScanner

- (void)parseString:(NSString *)str sizeX:(int *)x sizeY:(int *)y
{
    NSScanner *scn = [NSScanner scannerWithString:str];
    [scn scanInt:x];
    [scn scanString:@"mm x " intoString:NULL];
    [scn scanInt:y];
}

并使用它:

NSString *s = @"50mm x 200mm";
int x, y;
[self parseString:s sizeX:&x sizeY:&y];
NSLog(@"X size: %d, Y size: %d", x, y);

答案 1 :(得分:2)

有趣的是,如果你有一个像10mm的字符串,那么你可以使用intValue从中提取10。所以做你想做的另一种方式是:

    NSString *s = @"10mm x 1000mm";
    NSArray *arr = [s componentsSeparatedByString:@"x"];
    int firstNum = [arr[0] intValue];
    int secondNum = [arr[1] intValue];
    NSLog(@"%d   %d",firstNum,secondNum);

答案 2 :(得分:0)

如果你想要更强大的东西,你可以试试正则表达式:

NSString * input = @"55 mm x 100mm" ;

NSRegularExpression * regex = [ NSRegularExpression regularExpressionWithPattern:@"([0-9]+).*x.*([0-9]+)" options:NSRegularExpressionCaseInsensitive error:NULL ] ;
NSArray * matches = [ regex matchesInString:input options:0 range:(NSRange){ .length = input.length } ] ;
NSTextCheckingResult * match = matches[0] ;

NSInteger width ;
{
    NSRange range = [ match rangeAtIndex:1 ] ;
    width = [[ input substringWithRange:range ] integerValue ] ;
}

NSInteger height ;
{
    NSRange range = [ match rangeAtIndex:2 ] ;
    height = [[ input substringWithRange:range ] integerValue ] ;
}