获取文件path的最后2个目录

我有一个文件path,例如/Users/Documents/New York/SoHo/abc.doc 。 现在我需要从这个path中检索/SoHo/abc.doc

我经历了以下几点:

  • stringByDeletingPathExtension – >用于从path中删除扩展名。
  • stringByDeletingLastPathComponent – >删除零件中的最后一个零件。

但是,我没有find任何方法来删除第一部分,并保留path的最后两部分。

NSString有负载的path处理方法,这将是一个耻辱不使用…

 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]; } 

我已经为你写了特别的function:

 - (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"]; 
  1. 通过发送一个pathComponents消息将string分成组件。
  2. 从结果数组中除去最后两个对象。
  3. 将两个path组件一起join到带有+pathWithComponents:的单个string中+pathWithComponents:

为什么不search“/”字符并确定path?

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);