有没有办法在 NSString stringWithFormat 中指定参数位置/索引? [英] Is there a way to specify argument position/index in NSString stringWithFormat?

查看:21
本文介绍了有没有办法在 NSString stringWithFormat 中指定参数位置/索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C# 的语法允许您在字符串格式说明符中指定参数索引,例如:

C# has syntax that allows you to specify the argument index in a string format specifier, e.g.:

string message = string.Format("Hello, {0}. You are {1} years old. How does it feel to be {1}?", name, age);

您可以多次使用参数,也可以省略使用提供的参数.另一个问题%[index的形式提到了C/C++的相同格式]$[格式],例如%1$i.我无法让 NSString 完全遵守这种语法,因为它在格式中省略参数时表现良好.以下无法按预期工作(EXC_BAD_ACCESS 因为它试图将 age 参数取消引用为 NSObject*):

You can use arguments more than once and also omit arguments that are provided from being used. Another question mentions the same formatting for C/C++ in the form of %[index]$[format], e.g. %1$i. I have not been able to get NSString to fully respect this syntax, because it does behave well when omitting arguments from the format. The following does not work as expected (EXC_BAD_ACCESS because it attempts to dereference the age parameter as a NSObject*):

int age = 23;
NSString * name = @"Joe";
NSString * message = [NSString stringWithFormat:@"Age: %2$i", name, age];

仅当格式中没有缺少参数时才考虑位置参数(这似乎是一个奇怪的要求):

The positional arguments are respected only if there are no missing arguments from the format (which seems to be an odd requirement):

NSString * message = [NSString stringWithFormat:@"Age: %2$i; Name: %1$@", name, age];

所有这些调用在 OS X 中都能正常工作:

All these calls work properly in OS X:

printf("Age: %2$i", [name UTF8String], age);
printf("Age: %2$i %1$s", [name UTF8String], age);

有没有办法在 Objective-C/Cocoa 中使用 NSString 来实现这一点?这对于本地化目的很有用.

Is there a way of accomplishing this using NSString in Objective-C / Cocoa? It would be useful for localization purposes.

推荐答案

NSString 和 CFString 支持可重新排序/位置参数.

NSString and CFString support reorderable/positional arguments.

NSString *string = [NSString stringWithFormat: @"Second arg: %2$@, First arg %1$@", @"<1111>", @"<22222>"];
NSLog(@"String = %@", string);

此外,请参阅 Apple 上的文档:字符串资源

这篇关于有没有办法在 NSString stringWithFormat 中指定参数位置/索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆