How to parse NSString by deleting 2 folders in a path in Objective-C

I need to parse an NSString in Objective-C .. ie if the input path string is / a / b / c / d, I need to parse the path string to get outout like / a / b /
How do I achieve this? input path line: / a / b / c / d expected output path line: / a / b / Please help me.

Thanks. Suse.

+6
source share
3 answers

You can use stringByDeletingLastPathComponent twice:

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

Returns /a/b .

+16
source

What about:

 NSString *path = @"/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 
+1
source
 NSString *path = @"/a/b/c/d"; int howManyFoldersNeedsToBeDeleded = 2; for (int i = 1; i <= howManyFoldersNeedsToBeDeleded; i++) { path = [path stringByDeletingLastPathComponent]; } NSLog(@"output : %@ \n\n",path); 
0
source

Source: https://habr.com/ru/post/897601/


All Articles