superllanboy
superllanboy

Reputation: 627

How can I extract numbers from an NSString?

I have an NSString data with the following and similar formats:

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

Can someone please advise how to extract the two separate numbers in each case?

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

And so on.

Upvotes: 0

Views: 224

Answers (3)

nielsbot
nielsbot

Reputation: 16022

If you want something more robust, you could try regular expressions:

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 ] ;
}

Upvotes: 0

rdelmar
rdelmar

Reputation: 104082

Interestingly, if you have a string like 10mm, then you can use intValue to extract the 10 from it. So another way to do what you want is:

    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);

Upvotes: 2

user529758
user529758

Reputation:

If the format is really, always

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

then you can use 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];
}

and use it like:

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

Upvotes: 2

Related Questions