按关键字格式化的Objective-C字符串

3
在Objective C中,是否有一种类似于python's str.format方法的格式化字符串的方式。我想要能够使用一些字典@{@"keyword_2": @"bar", @"keyword_1": @"foo"}替换带有关键字@"this is {keyword_1}, and this is {keyword_2}"的字符串,并生成一个新的字符串@"this is foo, and this is bar"。在Objective C中,这可能看起来像这样:
[NSString stringWithKeywordFormat:@"hello {user_name}, today is {day_of_week}!" keywords:@{@"user_name":@"Jack", @"day_of_week":@"Thursday"}];

1
没有内置的东西。不过,GRMustache 模板库似乎实现了类似的功能(我自己从未使用过)。 - omz
@omz。感谢您的指引,我会去查看一下。 - Phillip Martin
2个回答

2

使用NSScanner类解析格式字符串很容易编写这样的函数。

在.h文件中声明一个NSString类别:

#import <Foundation/Foundation.h>

@interface NSString (KeywordFormat)
+ (NSString *)stringWithKeywordFormat:(NSString *)format keywords:(NSDictionary *)dictionary;
@end

.m文件中的实现如下:
#import "NSString+KeywordFormat.h"

@implementation NSString (KeywordFormat)

+ (NSString *)stringWithKeywordFormat:(NSString *)format keywords:(NSDictionary *)dictionary
{
    NSMutableString *result = [NSMutableString string];

    NSScanner *scanner = [NSScanner scannerWithString:format];
    [scanner setCharactersToBeSkipped:nil];

    NSString *temp;
    while ( ![scanner isAtEnd] )
    {
        // copy characters to the result string until a { is found
        if ( [scanner scanUpToString:@"{" intoString:&temp] )
            [result appendString:temp];
        if ( [scanner isAtEnd] )
            break;

        // swallow the { character
        if ( ![scanner scanString:@"{" intoString:NULL] )
            break;
        if ( [scanner isAtEnd] )
            break;

        // get the keyword
        if ( ![scanner scanUpToString:@"}" intoString:&temp] )
            break;
        if ( [scanner isAtEnd] )
            break;

        // swallow the } character
        if ( ![scanner scanString:@"}" intoString:NULL] )
            break;

        // lookup the keyword in the dictionary, and output the value
        [result appendFormat:@"%@", dictionary[temp]];
    }

    return( [result copy] );
}

@end

字符串中可能应该有一种方式来表示字面上的 {,而不是表示变量的开始。 - rmaddy
1
@rmaddy同意。我决定把那部分作为读者的练习留下来。 - user3386109

0

不在标准的一方苹果库中,没有。我也从未在第三方库中看到过任何东西。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接