NSString stringWithFormat:具有随机数量的替换
我正在读取字符串列表,每个字符串都可以包含多个占位符 (%@)。我想使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以通过指定位置来告诉
stringWithFormat:
重复使用相同的参数。请参阅 字符串格式说明符。示例:您还可以使用 stringByReplacingOccurrencesOfString:withString: 替换“%@”的所有实例,但这要求您单独执行每个参数,并且它们必须是字符串:
You can tell
stringWithFormat:
to use the same argument repeatedly by specifying the position. See String Format Specifiers. Example: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: