当我有一个路径时,我可以在Python中使用os.path.split()来获取目录名和文件名。
>>> x = '/a/b/c/hello.txt'
>>> import os.path
>>> os.path.split(x)
('/a/b/c', 'hello.txt')
Objective-C / cocoa中的等效功能是什么?
答案 0 :(得分:4)
NSString *a = @"/a/b/c/hello.txt";
NSArray *path = [a pathComponents];
NSArray *startOfPath = [path subarrayWithRange:NSMakeRange(0, [path count]-2)];
[NSString pathWithComponents:startOfPath]; // /a/b/c
[a lastPathComponent]; // hello.txt
答案 1 :(得分:3)
有一种更简单的方法(好吧,比乱搞子阵列);查看NSPathUtilities.h。
- (NSString *)lastPathComponent;
- (NSString *)stringByDeletingLastPathComponent;
- (NSString *)stringByAppendingPathComponent:(NSString *)str;
- (NSString *)pathExtension;
- (NSString *)stringByDeletingPathExtension;
- (NSString *)stringByAppendingPathExtension:(NSString *)str;
- (NSArray *)stringsByAppendingPaths:(NSArray *)paths;
使用“/a/b/c/hello.txt”示例:
NSString *path = @"/a/b/c/hello.txt";
NSString *fileName = [path lastPathComponent];
// 'hello.txt'
NSString *basePath = [path stringByDeletingLastPathComponent];
// '/a/b/c'
NSString *newPath = [basePath stringByAppendingPathComponent:@"goodbye.txt"];
// '/a/b/c/goodbye.txt'
等等......
答案 2 :(得分:0)
NSString有 - (NSArray *)pathComponents
。