从没有时间戳和文件扩展名的URL获取文件名 - 目标C.

时间:2017-02-15 07:08:55

标签: ios objective-c

从不同的网址下面我只需要文件名

  

网址1 =上传/ 4 / jobs / 2017-02-15-05-17-05pmThe_Wolf_of_Wall_Street _-_ Jordan_Belfort.pdf   网址2 =上传/ 4 / jobs / 2017-02-15-05-17-05ammaster.jpg

我需要的是

Result1 = The_Wolf_of_Wall_Street_-_Jordan_Belfort
Result2 = master

3 个答案:

答案 0 :(得分:1)

试试这个:

let name  = "uploads/4/jobs/2017-02-15-05-17-05pmThe_Wolf_of_Wall_Street_-_Jordan_Belfort.pdf"
var names = name.components(separatedBy: "/")
let lastComponent = names[names.count - 1]

var nameOfFile:String = ""
let pm = lastComponent.components(separatedBy: "pm")
let am = lastComponent.components(separatedBy: "am")
if(pm.count > 1){
    nameOfFile = pm[1]
} else if(am.count > 1){
    nameOfFile = am[1]
}
print(nameOfFile)

答案 1 :(得分:1)

如果您的网址将始终遵循开始命名格式。

  let urlStr = "uploads/4/jobs/2017-02-15-05-17-05pmThe_Wolf_of_Wall_Street_-_Jordan_Belfort.pdf"
  let indexStart = urlStr.index(urlStr.startIndex, offsetBy: +36)
  let str = urlStr.substring(from: indexStart )
  let indexEnd = str.index(str.endIndex, offsetBy: -4)
  let name = str.substring(to: indexEnd )

答案 2 :(得分:0)

您可以尝试以下Objective-C代码

NSString* string = @"uploads/4/jobs/2017-02-15-05-17-05pmThe_Wolf_of_Wall_Street_-_Jordan_Belfort.pdf";

NSArray* array = [string componentsSeparatedByString:@"/"];
NSString* lastElement = [array lastObject];

NSArray* finalArrayForPM = [lastElement componentsSeparatedByString:@"pm"];
NSArray* finalArrayForAM = [lastElement componentsSeparatedByString:@"am"];
if (finalArrayForPM.count > 1) {
    NSString* fileName = [[finalArrayForPM lastObject] stringByDeletingPathExtension];
    NSLog(@"The fileName is %@",fileName);
} else if (finalArrayForAM.count > 1) {
    NSString* fileName = [[finalArrayForAM lastObject] stringByDeletingPathExtension];
    NSLog(@"The fileName is %@",fileName);
}

希望这有帮助。