Get last path part from NSString

耗尽温柔 提交于 2019-11-27 11:44:09

问题


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.


回答1:


You can also use

NSString *sub = [@"http://www.abc.com/news/read/welcome-new-gig/03276" lastPathComponent];



回答2:


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



回答3:


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]



回答4:


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



回答5:


If the last part of the string is always the same length (5 characters) you could use this method to extract the last part:

- (NSString *)substringFromIndex:(NSUInteger)anIndex

Use the length of the string to determine the start index.

Something like this:

NSString *inputStr = @"http://www.abc.com/news/read/welcome-new-gig/03276";
NSString *newStr = [inputStr substringFromIndex:[inputStr length]-5];
NSLog(@"These are the last five characters of the string: %@", newStr);

(Code not tested)




回答6:


NSString *str = @"http://www.abc.com/news/read/welcome-new-gig/03276";  
NSArray *arr = [str componentSeparatedBy:@"gig/"];  
NSString *strSubStringDigNum = [arr objectAtIndex:1];  

strSubStringDigNum will have the value 03276




回答7:


Try this:

NSString *myUrl = @"http://www.abc.com/news/read/welcome-new-gig/03276";

NSString *number = [[myUrl componentsSeparatedByString:@"/"] objectAtIndex: 5];


来源:https://stackoverflow.com/questions/6440187/get-last-path-part-from-nsstring

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!