gpt4 book ai didi

cocoa - NSString stringWithFormat : with random number of replacements

转载 作者:行者123 更新时间:2023-12-03 16:33:28 25 4
gpt4 key购买 nike

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

最佳答案

您可以通过指定位置来告诉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"];

关于cocoa - NSString stringWithFormat : with random number of replacements,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5670240/

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