我有一个文件路径,例如/Users/Documents/New York/SoHo/abc.doc
。现在我需要从这条路径检索/SoHo/abc.doc
。获取文件路径的最后2个目录
我已经通过了如下:
stringByDeletingPathExtension
- >用来删除该路径延伸。stringByDeletingLastPathComponent
- >删除零件中的最后一个零件。
但是我没有找到任何方法删除第一部分并保留路径的最后两部分。
我有一个文件路径,例如/Users/Documents/New York/SoHo/abc.doc
。现在我需要从这条路径检索/SoHo/abc.doc
。获取文件路径的最后2个目录
我已经通过了如下:
stringByDeletingPathExtension
- >用来删除该路径延伸。stringByDeletingLastPathComponent
- >删除零件中的最后一个零件。但是我没有找到任何方法删除第一部分并保留路径的最后两部分。
为什么不搜索'/'字符并确定路径?
pathComponents
消息将字符串分成组件。+pathWithComponents:
我写功能特供您:
- (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"];
的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];
}
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);