2011-11-10 2 views
9

파일 경로는 예를 들어 /Users/Documents/New York/SoHo/abc.doc입니다. 이제이 경로에서 /SoHo/abc.doc을 검색해야합니다.파일 경로의 마지막 두 디렉토리 얻기

나는 다음과 같은 겪었 :

  • 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 = // 경로를 얻으십시오;

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

관련 문제