gpt4 book ai didi

objective-c - 有没有办法在 NSString stringWithFormat 中指定参数位置/索引?

转载 作者:IT老高 更新时间:2023-10-28 11:23:59 25 4
gpt4 key购买 nike

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

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

您可以多次使用参数,也可以省略使用提供的参数。 Another question%[index]$[format] 的形式提及 C/C++ 的相同格式,例如%1$i。我无法让 NSString 完全 遵守此语法,因为在格式中省略参数 时它确实表现良好。以下不按预期工作(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 来完成这个?这对于本地化目的很有用。

最佳答案

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

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

另外,请参阅 Apple: String Resources 上的文档

关于objective-c - 有没有办法在 NSString stringWithFormat 中指定参数位置/索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1063843/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com