-->

Getting the last 2 directories of a file path

2019-06-16 10:51发布

问题:

I have a file path of, for example /Users/Documents/New York/SoHo/abc.doc. Now I need to just retrieve /SoHo/abc.doc from this path.

I have gone through the following:

  • stringByDeletingPathExtension -> used to delete the extension from the path.
  • stringByDeletingLastPathComponent -> to delete the last part in the part.

However I didn't find any method to delete the first part and keep the last two parts of a path.

回答1:

NSString has loads of path handling methods which it would be a shame not to use...

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


回答2:

I've written function special for you:

- (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;
}

Just call:

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


回答3:

  1. Divide the string into components by sending it a pathComponents message.
  2. Remove all but the last two objects from the resulting array.
  3. Join the two path components together into a single string with +pathWithComponents:


回答4:

Why not search for the '/' characters and determine the paths that way?



回答5:

NSString* theLastTwoComponentOfPath; NSString* filePath = //GET Path;

    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 (@"The last Two Components=%@", theLastTwoComponentOfPath);