2011-11-10 53 views
9

我有一个文件路径,例如/Users/Documents/New York/SoHo/abc.doc。现在我需要从这条路径检索/SoHo/abc.doc获取文件路径的最后2个目录

我已经通过了如下:

  • stringByDeletingPathExtension - >用来删除该路径延伸。
  • stringByDeletingLastPathComponent - >删除零件中的最后一个零件。

但是我没有找到任何方法删除第一部分并保留路径的最后两部分。

回答

0

为什么不搜索'/'字符并确定路径?

2
  1. 通过发送一个pathComponents消息将字符串分成组件。
  2. 从结果数组中删除除最后两个对象以外的所有对象。
  3. 加入两个通道部件连成一个单一的字符串+pathWithComponents:
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"]; 
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]; 
} 
0

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

相关问题