今天是端午节.,所以就使用百度首页的龙舟动态图地址做实验
做测试一般只需要创建 "OS X" 的 "Command Line Tool" 即可。
#import <Foundation/Foundation.h>
void getFileName(NSString* urlString) {
//1、lastPathComponent
NSString *fileName = [urlString lastPathComponent];
NSLog(@"1、lastPathComponent\n%@", fileName);
//2、pathComponents
NSArray *urlComponentArray = [urlString pathComponents];
NSLog(@"2、pathComponents\n%@", [urlComponentArraylastObject]);
//3、componentsSeparatedByString字符串分割法
NSArray *urlSeparatedStr = [urlString componentsSeparatedByString:@"/"];
NSLog(@"3、componentsSeparatedByString\n%@", [urlSeparatedStrlastObject]);
//4、NSRange尾部截取法
NSRange range = [urlStringrangeOfString:@"/"options:(NSBackwardsSearch)];
if(range.location ==NSNotFound) {
fileName = urlString;
} else {
fileName = [urlString substringFromIndex:range.location+1];
}
NSLog(@"4、NSRange\n%@", fileName);
}
int main(int argc,const char * argv[]) {
@autoreleasepool {
// insert code here...
NSLog(@"Hello, World! chy龙神");
NSString *urlString =@"https://i-blog.csdnimg.cn/blog_migrate/020cc1d0e07f0ea5b18ac4bbf2b0ace1.gif";
NSLog(@"绝对路径");
getFileName(urlString);
NSLog(@"相对路径");
urlString = @"2016_6_9logo_e5230b7f39f078d288a313971a7fea56.gif";
getFileName(urlString);
}
return 0;
}
运行截图
从结果可以看出,以上4种方法对于“绝对路径”和“相对路径”均适用