使用可变数量的键和格式构建字符串

时间:2011-05-26 19:50:23

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

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

[self displayMyDataWithTheseKeys:myKeyArray inThisFormat:myFormat];

其中,例如,

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

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

但是,myFormat可能会更改,并且数组中的键数也可能会有所不同。

如果数组中的元素数总是2,那么这将是微不足道的。但是,我如何处理可变数量的元素?

2 个答案:

答案 0 :(得分:0)

对此没有真正的内置方法,但使用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];
    }
}

答案 1 :(得分:-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]];
    }