【问题标题】:Getting the last 2 directories of a file path获取文件路径的最后两个目录
【发布时间】:2011-12-26 03:42:14
【问题描述】:
我有一个文件路径,例如/Users/Documents/New York/SoHo/abc.doc。现在我只需要从这条路径中检索/SoHo/abc.doc。
我经历了以下:
-
stringByDeletingPathExtension -> 用于从路径中删除扩展名。
-
stringByDeletingLastPathComponent -> 删除部分的最后一部分。
但是我没有找到任何方法来删除路径的第一部分并保留路径的最后两部分。
【问题讨论】:
标签:
iphone
objective-c
ios
xcode
ipod-touch
【解决方案1】:
NSString* theLastTwoComponentOfPath;
NSString* filePath = //获取路径;
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(@"最后两个组件=%@", theLastTwoComponentOfPath);
【解决方案2】:
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];
}
【解决方案3】:
我为你写了特别的函数:
- (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"];
【解决方案4】:
- 通过向其发送
pathComponents 消息将字符串分成多个组件。
- 从结果数组中删除除最后两个对象之外的所有对象。
- 使用
+pathWithComponents: 将两个路径组件连接到一个字符串中