在Objective-C扩展名之前为文件名添加后缀的最简单方法是什么?
示例
image.png
~ipad
image~ipad.png
答案 0 :(得分:12)
NSString
有一大堆与路径相关的方法:
NSString * appendSuffixToPath(NSString * path, NSString * suffix) {
NSString * containingFolder = [path stringByDeletingLastPathComponent];
NSString * fullFileName = [path lastPathComponent];
NSString * fileExtension = [fullFileName pathExtension];
NSString * fileName = [fullFileName stringByDeletingPathExtension];
NSString * newFileName = [fileName stringByAppendingString:suffix];
NSString * newFullFileName = [newFileName stringByAppendingPathExtension:fileExtension];
return [containingFolder stringByAppendingPathComponent:newFullFileName];
}
(是的,你可以用很少的变量做到这一点,但我想说清楚每个方法在做什么)
答案 1 :(得分:2)
知道它已经老了但是有人可能会喜欢这个Swift解决方案
extension String {
func appendSuffixBeforeExtension(suffix: String) -> String {
let regex = NSRegularExpression(pattern: "(\\.\\w+$)", options: nil, error: nil)
return regex!.stringByReplacingMatchesInString(self, options: nil, range: NSMakeRange(0, count(self)), withTemplate: "\(suffix)$1")
}
}
然后这样称呼它
let mytxt = "/somepath/file.jpg"
let retina = mytxt.appendSuffixBeforeExtension("@x2")
答案 2 :(得分:1)
使用URL
方法:
let suffixedFileURL = fileURL
.deletingLastPathComponent()
.appendingPathComponent(
fileURL
.deletingPathExtension()
.lastPathComponent
.appending("suffix")
)
.appendingPathExtension(fileURL.pathExtension)
答案 3 :(得分:0)
上述解决方案不适用于文件名,例如../ filename.pvr.ccz
所以我稍微调整了一下来考虑多个文件扩展名:
-(NSString *)appendSuffixToPath:(NSString *)pPath withSuffix:(NSString *)pSuffix {
NSString * containingFolder = [pPath stringByDeletingLastPathComponent];
NSString * fullFileName = [pPath lastPathComponent];
NSMutableArray *extensions = [[NSMutableArray alloc] init];
NSString * fileExtension = [fullFileName pathExtension];
[extensions addObject:fileExtension];
NSString * fileName = [fullFileName stringByDeletingPathExtension];
while([fileName pathExtension].length > 0){
fileExtension = [fileName pathExtension];
[extensions addObject:fileExtension];
fileName = [fileName stringByDeletingPathExtension];
}
NSString * newFileName = [fileName stringByAppendingString:pSuffix];
NSString * newFullFileName = newFileName;
while ([extensions count] > 0) {
newFullFileName = [newFullFileName stringByAppendingPathExtension:[extensions objectAtIndex:((int)[extensions count] - 1)]];
[extensions removeObjectAtIndex:((int)[extensions count] - 1)];
}
NSString *result = [containingFolder stringByAppendingPathComponent:newFullFileName];
return result;
}