Reputation: 1429
I have an NSString that gets assigned a string value. How do I take this NSString
and insert @"-thumbnail"
between the file's name and its extension?
In other words, how do I go from:
NSString *fileName = @"myFile.png";
to:
NSString *thumbnailName = [NSString someMagicFunction...]
NSLog(@"%@", thumbnailName); // Should Output "myFile-thumbnail.png"
Upvotes: 2
Views: 1767
Reputation: 15013
We've got an opensource category for just that: -[NSString ks_stringWithPathSuffix:]
Upvotes: 0
Reputation: 75067
If you are certain of your filenames, you could also simply do:
[NSString stringByReplacingOccurrencesOfString:@"." withString:@"-thumbnail."]
But the path handling stuff is cleaner (doesn't care how many "." you have in the name) and good to know about for trickier cases.
Upvotes: 1
Reputation: 119184
The NSString additions for path components can come in handy, specifically: pathExtension and stringByDeletingPathExtension
Edit: see also: stringByAppendingPathExtension: (as pointed out by Dave DeLong)
NSString * ext = [fileName pathExtension];
NSString * baseName = [fileName stringByDeletingPathExtension];
NSString * thumbBase = [baseName stringByAppendingString:@"-thumbnail"];
NSString * thumbnailName = [thumbBase stringByAppendingPathExtension:ext];
If you really want that magicFunction
to exist, you can add a category method to NSString like so:
@interface NSString (MoreMagic)
- (NSString *)stringByAddingFileSuffix:(NSString *)suffix;
@end
@implementation NSString (MoreMagic)
- (NSString *)stringByAddingFileSuffix:(NSString *)suffix
{
NSString * extension = [self pathExtension];
NSString * baseName = [self stringByDeletingPathExtension];
NSString * thumbBase = [baseName stringByAppendingString:suffix];
return [thumbBase stringByAppendingPathExtension:extension];
}
@end
To be used as follows:
NSString * thumbnailName = [fileName stringByAddingFileSuffix:@"-thumbnail"];
Upvotes: 11