Getting the last 2 directories of a file path
Asked Answered
S

5

9

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.

Strongminded answered 10/11, 2011 at 12:45 Comment(0)
A
11

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];
}
Ammadis answered 10/11, 2011 at 13:6 Comment(0)
R
3

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"];
Reactionary answered 10/11, 2011 at 13:1 Comment(0)
A
2
  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:
Attemper answered 10/11, 2011 at 12:56 Comment(0)
R
0

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

Recreant answered 10/11, 2011 at 12:54 Comment(0)
C
0

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);

Custody answered 2/8, 2013 at 12:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.