Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get last path part from NSString

Hi all i want extract the last part from string which is a four digit number '03276' i:e http://www.abc.com/news/read/welcome-new-gig/03276

how can i do that.

like image 753
Mobile Developer iOS Android Avatar asked Jun 22 '11 12:06

Mobile Developer iOS Android


4 Answers

You can also use

NSString *sub = [@"http://www.abc.com/news/read/welcome-new-gig/03276" lastPathComponent];
like image 178
Pierre Avatar answered Oct 06 '22 01:10

Pierre


If you know how many characters you need, you can do something like this:

NSString *string = @"http://www.abc.com/news/read/welcome-new-gig/03276";
NSString *subString = [string substringFromIndex:[string length] - 5];

If you just know that it's the part after the last slash, you can do this:

NSString *string = @"http://www.abc.com/news/read/welcome-new-gig/03276";
NSString *subString = [[string componentsSeparatedByString:@"/"] lastObject];
like image 38
Morten Fast Avatar answered Oct 05 '22 23:10

Morten Fast


Since *nix uses the same path separators as URL's this will be valid as well.

[@"http://www.abc.com/news/read/welcome-new-gig/03276" lastPathComponent]
like image 25
Joe Avatar answered Oct 06 '22 01:10

Joe


If you know the length of the number, and it's not gonna change, it can be as easy as:

NSString *result = [string substringFromIndex:[string length] - 4];
like image 28
EmilioPelaez Avatar answered Oct 05 '22 23:10

EmilioPelaez