【问题标题】:Build string with variable number of keys and formats构建具有可变数量的键和格式的字符串
【发布时间】:2011-09-02 21:46:11
【问题描述】:

我有一个包含我的数据的 NSDictionary 对象。我正在传递一个键名数组和我的数据的字符串表示的显示格式。

[self displayMyDataWithTheseKeys:myKeyArray inThisFormat:myFormat];

例如在哪里

myKeyArray = [NSArray arrayWithObjects: @"Key1", @"Key2", nil];

myFormat = [NSString stringWithString: @"%@ to the %@ degree"];

但是,myFormat 可能会发生变化,并且数组中的键数也可能会发生变化。

如果数组中的元素数始终为 2,这将是微不足道的。但是,如何处理可变数量的元素?

【问题讨论】:

  • 您可以扫描 myFormat 字符串中出现的任何 %@、%i、%d、...,将其拆分为仅包含单个格式说明符的子字符串,然后执行格式替换一次-对所有这些子字符串逐一进行,最后将所有内容放在一个字符串中。不过我还没试过。

标签: iphone objective-c nsstring ipad string-formatting


【解决方案1】:

使用:stringByAppendingString

这是一个如何使用它的示例:

NSString *someString = @"String";

someString = [someString stringByAppendingString:[NSString stringWithFormat:@"%@",variable1]];
someString = [someString stringByAppendingString:[NSString stringWithFormat:@"%@",variable2]];
someString = [someString stringByAppendingString:[NSString stringWithFormat:@"%@",variable3]];

...等等

如果你有一个键数组想要放入一个字符串中:

NSString *string = @"And the keys are:\n";

    for(int i = 0; i < [array count]; i++)
    {
        NSString *thisKey = (NSString *)[array objectAtIndex:i];

        string = [string stringByAppendingString:[NSString stringWithFormat:@"Key number %d is %@",i,thisKey]];
    }

【讨论】:

  • 但是,这不会给我想要的格式。
  • 感谢您提供帮助,但这仍然无法获得我想要的格式...您的解决方案忽略了 myFormat 变量,它显示了包括所有变量在内的格式。
【解决方案2】:

并没有真正的内置方法,但使用NSScanner 解析格式字符串相对容易。这是一个简单的例子,它只处理%@ 格式说明符,但由于NSArray 中的所有元素都是对象而不是原始类型,所以这无关紧要:

NSArray *myKeyArray = [NSArray arrayWithObjects: @"Key1", @"Key2", nil];
NSString *myFormat = [NSString stringWithString: @"%@ to the %@ degree"];

NSMutableString *result = [NSMutableString string];
NSScanner *scanner = [NSScanner scannerWithString:myFormat];
[scanner setCharactersToBeSkipped:[NSCharacterSet illegalCharacterSet]];
int i = 0;
while (![scanner isAtEnd]) {
    BOOL scanned = [scanner scanString:@"%@" intoString:NULL];
    if (scanned) {
        if (i < [myKeyArray count]) {
            [result appendString:[myKeyArray objectAtIndex:i]];
            i++;
        } else {
            //Handle error: Number of format specifiers doesn't 
            //match number of keys in array...
        }
    }
    NSString *chunk = nil;
    [scanner scanUpToString:@"%@" intoString:&chunk];
    if (chunk) {
        [result appendString:chunk];
    }
}

【讨论】:

    猜你喜欢
    • 2020-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多