我正在读一个字符串列表,每个字符串都可以包含许多占位符(%@)。我想使用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"];
}
答案 0 :(得分:3)
您可以通过指定位置告诉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"];