2011-09-19 1 views
6

Objective-CでNSStringを解析する必要があります。つまり、入力パス文字列が/ a/b/c/dの場合、パス文字列を解析する必要があります/ a/b/
どのように私はそれを達成するのですか? 入力パス文字列:/ a/b/c/d 予想される出力パス文字列:/ a/b/ 私を助けてください。Objective-Cでパス内の2つのフォルダを削除してNSStringを解析する方法

ありがとうございます。 Suse。

答えて

16

あなたは二回stringByDeletingLastPathComponentを使用することができます。

NSString *pathStr = @"https://stackoverflow.com/a/b/c/d"; 
NSString *path = [[pathStr stringByDeletingLastPathComponent] stringByDeletingLastPathComponent]; 
NSLog(@"%@", path); 

返し/a/bを。

+0

そんなに – suse

+0

はそんなに.. Upvotedありがとうありがとう:) – Karun

0
NSString *path = @"https://stackoverflow.com/a/b/c/d"; 


int howManyFoldersNeedsToBeDeleded = 2; 

for (int i = 1; i <= howManyFoldersNeedsToBeDeleded; i++) { 


    path = [path stringByDeletingLastPathComponent]; 




} 



NSLog(@"output : %@ \n\n",path); 
1

方法について:

NSString *path = @"https://stackoverflow.com/a/b/c/d"; 
NSArray *components = [path pathComponents] 

NSLog(@"%@", [components objectAtIndex: 1]); // <- output a 
NSLog(@"%@", [components objectAtIndex: 2]); // <- output b 
NSLog(@"%@", [components lastObject]); // <- output d 
関連する問題