Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add suffix to file name before extension

What's the simplest way to add a suffix to a file name before the extension in Objective-C?

Example

  • Original name: image.png
  • Suffix: ~ipad
  • Result: image~ipad.png
like image 811
hpique Avatar asked Dec 03 '22 04:12

hpique


1 Answers

NSString has a whole bunch of path-related methods:

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];
}

(Yes, you could do that with a lot fewer variables, but I wanted to make it clear what each method was doing)

like image 191
Dave DeLong Avatar answered Dec 19 '22 13:12

Dave DeLong