2011-11-10 12 views
9

Ho un percorso file, ad esempio /Users/Documents/New York/SoHo/abc.doc. Ora ho bisogno di recuperare semplicemente /SoHo/abc.doc da questo percorso.Ottenere le ultime 2 directory di un percorso file

Ho passato con il seguente:

  • stringByDeletingPathExtension -> utilizzato per eliminare l'estensione dal percorso.
  • stringByDeletingLastPathComponent -> per eliminare l'ultima parte nella parte.

Tuttavia non ho trovato alcun metodo per eliminare la prima parte e mantenere le ultime due parti di un percorso.

risposta

0

Perché non cercare i caratteri "/" e determinare i percorsi in questo modo?

2
  1. Dividere la stringa in componenti inviandola un messaggio pathComponents.
  2. Rimuovi tutti gli ultimi due oggetti dall'array risultante.
  3. unire le due componenti del percorso insieme in una singola stringa con +pathWithComponents:
3

ho scritto funzione speciale per voi:

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

Basta chiamare:

[self directoryAndFilePath:@"/Users/Documents/New York/SoHo/abc.doc"]; 
11

NSString ha un sacco di metodi di trattamento del percorso che sarebbe un peccato non usare ...

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 (@ "L'ultima due componenti =% @", theLastTwoComponentOfPath);

Problemi correlati