NSString stringWithFormat:具有随机数量的替换

发布于 2024-11-01 19:07:58 字数 572 浏览 3 评论 0原文

我正在读取字符串列表,每个字符串都可以包含多个占位符 (%@)。我想使用 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"];
}

I am reading in a list of strings, each of which can contain a number of placeholders (%@). I would like to use stringWithFormat: to insert the appropriate value but this works for only one substitution. What can I use to substitute all the values? Is there some sort of string substitution function?

This is an example of what I am trying to do (a little bit of pseudo code):

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"];
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

辞取 2024-11-08 19:07:59

您可以通过指定位置来告诉 stringWithFormat: 重复使用相同的参数。请参阅 字符串格式说明符。示例:

[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"];

You can tell stringWithFormat: to use the same argument repeatedly by specifying the position. See String Format Specifiers. Example:

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

You could also use stringByReplacingOccurrencesOfString:withString: to replace all instances of "%@", but this requires that you do each argument separately and they must be strings:

[@"%@ is the first argument, and so is %@" stringByReplacingOccurrencesOfString:@"%@" withString:@"this"];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文