2011-11-10 19 views
9

की अंतिम 2 निर्देशिकाएं प्राप्त करना मेरे पास फ़ाइल पथ है, उदाहरण के लिए /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

एनएसएसटींग * theLastTwoComponentOfPath; एनएसएसटींग * 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);

संबंधित मुद्दे