2011-11-10 96 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);

相關問題