我有一個文件路徑,例如/Users/Documents/New York/SoHo/abc.doc
。現在我需要從這條路徑檢索/SoHo/abc.doc
。獲取文件路徑的最後2個目錄
我已經通過了如下:
stringByDeletingPathExtension
- >用來刪除該路徑延伸。stringByDeletingLastPathComponent
- >刪除零件中的最後一個零件。
但是我沒有找到任何方法刪除第一部分並保留路徑的最後兩部分。
我有一個文件路徑,例如/Users/Documents/New York/SoHo/abc.doc
。現在我需要從這條路徑檢索/SoHo/abc.doc
。獲取文件路徑的最後2個目錄
我已經通過了如下:
stringByDeletingPathExtension
- >用來刪除該路徑延伸。stringByDeletingLastPathComponent
- >刪除零件中的最後一個零件。但是我沒有找到任何方法刪除第一部分並保留路徑的最後兩部分。
爲什麼不搜索'/'字符並確定路徑?
pathComponents
消息將字符串分成組件。+pathWithComponents:
我寫功能特供您:
- (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"];
的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 * 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);