Search code examples
objective-cnsstringsubstringnsrange

How to substract string correctly?


i've got two strings in two objects:

<div align="center"><img src="http://farm9.staticflickr.com/8448/7882675644_76605a2a3d_b.jpg" border="0" alt="" /></div><

<img src="http://farm9.staticflickr.com/8425/7881940452_d2a8e898a3_o.png" border="0" alt="" /><br /><

And i'm trying to substract link to image.

i get link by using object method:

NSMutableString *string = [NSMutableString stringWithString:description];

int left = [string rangeOfString:@"http://"].location;

int right = 0;

if ([string rangeOfString:@".jpg"].location != NSNotFound) {
    right = [string rangeOfString:@".jpg"].location;
}
else if ([string rangeOfString:@".png"].location != NSNotFound){
    right = [string rangeOfString:@".png"].location;
}


NSString *sub = [string substringWithRange:NSMakeRange(left, right)];

NSLog(@"%@",sub);

but the problem is when i print what i substract:

2012-08-29 18:53:30.716 MyApple[56335:c07] http://farm9.staticflickr.com/8448/7882675644_76605a2a3d_b.jpg" border="0" alt="" /></di
2012-08-29 18:53:30.717 MyApple[56335:c07] http://farm9.staticflickr.com/8425/7881940452_d2a8e898a3_o.png" bord

IMO i substract from http:// to .jpg or .png, but it's not working correctly.

Thanks for help.


Solution

  • The second argument of NSMakeRange() is the length, so you probably need

    NSString *sub = [string substringWithRange:NSMakeRange(left, right - left)];
    

    You should also take a look at NSRegularExpression!