我有一个文件路径,例如 /Users/Documents/New York/SoHo/abc.doc
,现在我需要从中获取 /SoHo/abc.doc
。
我已经尝试了以下方法:
stringByDeletingPathExtension
-> 用于删除路径中的扩展名。stringByDeletingLastPathComponent
-> 用于删除路径中的最后一部分。
然而,我没有找到任何可以删除第一部分并保留路径中后两个部分的方法。
我有一个文件路径,例如 /Users/Documents/New York/SoHo/abc.doc
,现在我需要从中获取 /SoHo/abc.doc
。
我已经尝试了以下方法:
stringByDeletingPathExtension
-> 用于删除路径中的扩展名。stringByDeletingLastPathComponent
-> 用于删除路径中的最后一部分。然而,我没有找到任何可以删除第一部分并保留路径中后两个部分的方法。
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 *)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"];
pathComponents
消息将字符串分解为组件。+pathWithComponents:
将两个路径组件连接成单个字符串。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);