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.
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];
}
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"];
Why not search for the '/' characters and determine the paths that way?
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);