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.

GEOCHET
  • 21,119
  • 15
  • 74
  • 98
james lobo
  • 463
  • 4
  • 10

5 Answers5

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];
}
jbat100
  • 16,757
  • 4
  • 45
  • 70
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"];
Nekto
  • 17,837
  • 1
  • 55
  • 65
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:
Ole Begemann
  • 135,006
  • 31
  • 278
  • 256
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);

Yogesh Lolusare
  • 2,162
  • 1
  • 24
  • 35
0

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

TigerCoding
  • 8,710
  • 10
  • 47
  • 72