【问题标题】:NSString stringWithFormat: with random number of replacementsNSString stringWithFormat:随机替换次数
【发布时间】:2011-04-15 07:09:56
【问题描述】:

我正在阅读一个字符串列表,每个字符串都可以包含多个占位符 (%@)。我想使用 stringWithFormat: 插入适当的值,但这仅适用于一次替换。我可以用什么来替换所有值?是否有某种字符串替换功能?

这是我正在尝试做的一个例子(一点点伪代码):

NSString[] patterns = { "my name is %@ every day", "my name is %@ and it will remain %@" };
foreach (NSString s in patterns )
{
    // sometimes the string has one substitution, and sometimes
    // more. The project where I am doing this throws a BAD_ACCESS
    // error if more than one substitution is required so need
    // to take a different approach?
    print [NSString stringWithFormat:s, "Jack"];
}

【问题讨论】:

  • 请贴出您目前拥有的代码。人们可以从那里提出建议。
  • +1 给黑蛙。你有数组或字典中的值吗?
  • 我添加了一个例子来说明我想要做什么。

标签: cocoa nsstring


【解决方案1】:

您可以通过指定位置告诉stringWithFormat: 重复使用相同的参数。见String Format Specifiers。示例:

[NSString stringWithFormat:@"%1$@ is the first argument, and so is %1$@",@"this"];
// creates "this is the first argument, and so is this"

您也可以使用stringByReplacingOccurrencesOfString:withString: 替换“%@”的所有实例,但这要求您单独执行每个参数并且它们必须是字符串:

[@"%@ is the first argument, and so is %@" stringByReplacingOccurrencesOfString:@"%@" withString:@"this"];

【讨论】:

  • 这可能会奏效......我回家后会检查一下 :-) 谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多