gpt4 book ai didi

iphone - NSString 问题

转载 作者:行者123 更新时间:2023-12-03 20:19:44 24 4
gpt4 key购买 nike

我有一个 NSString,它被分配了一个字符串值。如何获取此 NSString 并在文件名及其扩展名之间插入 @"-thumbnail"

换句话说,我如何从:

NSString *fileName = @"myFile.png";

至:

NSString *thumbnailName = [NSString someMagicFunction...]
NSLog(@"%@", thumbnailName); // Should Output "myFile-thumbnail.png"

最佳答案

路径组件的 NSString 添加可以派上用场,特别是: pathExtensionstringByDeletingPathExtension

编辑:另请参阅:stringByAppendingPathExtension: (正如 Dave DeLong 所指出的)

NSString * ext = [fileName pathExtension];
NSString * baseName = [fileName stringByDeletingPathExtension];
NSString * thumbBase = [baseName stringByAppendingString:@"-thumbnail"];
NSString * thumbnailName = [thumbBase stringByAppendingPathExtension:ext];

如果你确实希望 magicFunction 存在,你可以向 NSString 添加一个类别方法,如下所示:

@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

使用方式如下:

NSString * thumbnailName = [fileName stringByAddingFileSuffix:@"-thumbnail"];

关于iphone - NSString 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4551214/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com