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 substitutio开发者_开发技巧n 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"];
}
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"];
精彩评论