C# 的语法允许您在字符串格式说明符中指定参数索引,例如:
string message = string.Format("Hello, {0}. You are {1} years old. How does it feel to be {1}?", name, age);
您可以多次使用参数,也可以省略使用时提供的参数。另一个问题 https://stackoverflow.com/questions/462580/string-format-for-c提到了 C/C++ 的相同格式,形式为%[index]$[format]
, e.g. %1$i
。我无法获取 NSStringfully尊重这种语法,因为它在以下情况下表现良好省略参数从格式来看。以下内容无法按预期工作(EXC_BAD_ACCESS,因为它尝试取消引用age
参数作为 NSObject*):
int age = 23;
NSString * name = @"Joe";
NSString * message = [NSString stringWithFormat:@"Age: %2$i", name, age];
仅当格式中没有丢失参数时,才会考虑位置参数(这似乎是一个奇怪的要求):
NSString * message = [NSString stringWithFormat:@"Age: %2$i; Name: %1$@", name, age];
所有这些调用在 OS X 中都能正常工作:
printf("Age: %2$i", [name UTF8String], age);
printf("Age: %2$i %1$s", [name UTF8String], age);
有没有办法在 Objective-C / Cocoa 中使用 NSString 来实现这一点?这对于本地化目的很有用。