我有一个文件路径,例如/Users/Documents/New York/SoHo/abc.doc
。现在我需要从这条路径中检索/SoHo/abc.doc
。
我已经完成了以下内容:
stringByDeletingPathExtension
- >用于从路径中删除扩展名。stringByDeletingLastPathComponent
- >删除部件中的最后一部分。但是我没有找到任何方法来删除第一部分并保留路径的最后两部分。
答案 0 :(得分:11)
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];
}
答案 1 :(得分: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"];
答案 2 :(得分:2)
pathComponents
消息将字符串划分为组件。+pathWithComponents:
答案 3 :(得分:0)
为什么不搜索'/'字符并确定路径?
答案 4 :(得分:0)
NSString * theLastTwoComponentOfPath; NSString * filePath = // GET路径;
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);