iOS 4种方法获取文件名

今天是端午节.,所以就使用百度首页的龙舟动态图地址做实验


做测试一般只需要创建 "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种方法对于“绝对路径”和“相对路径”均适用





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值