tags:

views:

83

answers:

3

Hi All,

Im trying to write a method that will pull out the ID from a URI String. My code below seems inefficient, what would be a better way of finding the id string?

NSString *aID = [[[NSString alloc] initWithString:@"http://www.example.com/id368907840?mt=8&uo=4"] autorelease];
NSArray *arrStr = [aID componentsSeparatedByString:@"/id"];
aID = [arrStr objectAtIndex:1];
arrStr = [aID componentsSeparatedByString:@"?mt="];
aID = [arrStr objectAtIndex:0];

The above leaves me with the NSString = 368907840

+3  A: 

You can use NSURL -lastPathComponent, NSString -stringByTrimmingCharactersInSet, and NSCharacterSet +letterCharacterSet to accomplish the same task as in the following example:

NSURL* url = [NSURL URLWithString:@"http://www.example.com/id368907840?mt=8&uo=4"];
NSString* lastpath = [url lastPathComponent]; // "id368907840"
NSCharacterSet* letters = [NSCharacterSet letterCharacterSet];
NSString* result = [lastpath stringByTrimmingCharactersInSet:letters]; // 368907840

Disclaimer: I haven't actually tried this, so you will need to try it yourself, but I believe this should work.

Michael Aaron Safyan
thanks i combined this with:lastpath = [lastpath substringFromIndex:2]; // "368907840"
Skeep
A: 

You could use a combination of subStringWithRange and rangeOfString, something along the lines of

NSString *aID = [[[NSString alloc] initWithString:@"http://www.example.com/id368907840?mt=8&uo=4"] autorelease];

int startIndex = [aID rangeOfString:@"id"].location + 2;
int length = [aID rangeOfString:@"mt"].location - startIndex - 1;

aID = [aID substringWithRange:NSMakeRange(startIndex, length)];
jkilbride
A: 

Use regular expressions. One of those cases where it's easier and more readable to use them.

Hwee-Boon Yar
i did not think there was regex in cocoa?
Skeep
Try http://regexkit.sourceforge.net/RegexKitLite/index.html
Hwee-Boon Yar