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\"];
}
    
已邀请:
您可以通过指定位置告诉
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\"];
    

要回复问题请先登录注册