获取文件路径的最后2个目录

时间:2011-11-10 12:45:38

标签: iphone objective-c ios xcode ipod-touch

我有一个文件路径,例如/Users/Documents/New York/SoHo/abc.doc。现在我需要从这条路径中检索/SoHo/abc.doc

我已经完成了以下内容:

  • stringByDeletingPathExtension - >用于从路径中删除扩展名。
  • stringByDeletingLastPathComponent - >删除部件中的最后一部分。

但是我没有找到任何方法来删除第一部分并保留路径的最后两部分。

5 个答案:

答案 0 :(得分:11)

NSString有很多路径处理方法,如果不使用它将是一种耻辱......

NSString* filePath = // something

NSArray* pathComponents = [filePath pathComponents];

if ([pathComponents count] > 2) {
   NSArray* lastTwoArray = [pathComponents subarrayWithRange:NSMakeRange([pathComponents count]-2,2)];
   NSString* lastTwoPath = [NSString pathWithComponents:lastTwoArray];
}

答案 1 :(得分:3)

我为你写了一个特别的功能:

- (NSString *)directoryAndFilePath:(NSString *)fullPath
{

    NSString *path = @"";
    NSLog(@"%@", fullPath);
    NSRange range = [fullPath rangeOfString:@"/" options:NSBackwardsSearch];
    if (range.location == NSNotFound) return fullPath;
    range = NSMakeRange(0, range.location);
    NSRange secondRange = [fullPath rangeOfString:@"/" options:NSBackwardsSearch range:range];
    if (secondRange.location == NSNotFound) return fullPath;
    secondRange = NSMakeRange(secondRange.location, [fullPath length] - secondRange.location);
    path = [fullPath substringWithRange:secondRange];
    return path;
}

请致电:

[self directoryAndFilePath:@"/Users/Documents/New York/SoHo/abc.doc"];

答案 2 :(得分:2)

  1. 通过发送pathComponents消息将字符串划分为组件。
  2. 从结果数组中删除除最后两个对象之外的所有对象。
  3. 使用+pathWithComponents:
  4. 将两个路径组件合并为一个字符串

答案 3 :(得分:0)

为什么不搜索'/'字符并确定路径?

答案 4 :(得分:0)

NSString * theLastTwoComponentOfPath;         NSString * filePath = // GET路径;

    NSArray* pathComponents = [filePath pathComponents];

    int last= [pathComponents count] -1;
    for(int i=0 ; i< [pathComponents count];i++){

        if(i == (last -1)){
             theLastTwoComponentOfPath = [pathComponents objectAtIndex:i];
        }
        if(i == last){
            theTemplateName = [NSString stringWithFormat:@"\\%@\\%@", theLastTwoComponentOfPath,[pathComponents objectAtIndex:i] ];
        }
    }

NSlog(@“最后两个组件=%@”,theLastTwoComponentOfPath);