2011-04-14 87 views
2

我正在阅读字符串列表,其中每个字符串都可以包含多个占位符(%@)。我想使用stringWithFormat:插入适当的值,但这只适用于一个替换。我可以用什么来替代所有的值?是否有某种字符串替换功能?NSString 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"]; 
} 
+2

请张贴的代码你现在拥有什么。从那里人们可以提出建议。 – 2011-04-14 22:16:52

+0

+1黑蛙。你是否有数组或字典中的值或什么? – 2011-04-14 23:01:19

+1

我添加了一个例子来说明我正在尝试做什么。 – Nippysaurus 2011-04-14 23:10:41

回答

3

你可以告诉stringWithFormat:通过指定位置重复使用相同的说法。见String Format Specifiers。例如:

[NSString stringWithFormat:@"%[email protected] is the first argument, and so is %[email protected]",@"this"]; 
// creates "this is the first argument, and so is this" 

你也可以使用stringByReplacingOccurrencesOfString:withString:取代“%@”的所有实例,但是这需要你单独做各的说法,他们必须是字符串:

[@"%@ is the first argument, and so is %@" stringByReplacingOccurrencesOfString:@"%@" withString:@"this"]; 
+0

这可能会诀窍...当我回家时会检查它:-)谢谢。 – Nippysaurus 2011-04-14 23:21:48