使用值的NSArray有效地创build占位符模板NSString

我正在尝试为FMDB提供一个实用方法,它将取值为NSArray,并根据数组中值的数量返回一个IN语句中使用的占位符的string。

我想不出创build这个string的优雅方式,我是否缺less一些NSString实用工具方法:

// The contents of the input aren't important. NSArray *input = @[@(55), @(33), @(12)]; // Seems clumsy way to do things: NSInteger size = [input count]; NSMutableArray *placeholderArray = [[NSMutableArray alloc] initWithCapacity:size]; for (NSInteger i = 0; i < size; i++) { [placeholderArray addObject:@"?"]; } NSString *output = [placeholderArray componentsJoinedByString:@","]; // Would return @"?,?,?" to be used with input 

那这个呢?

 NSArray *input = @[@(55), @(33), @(12)]; NSUInteger count = [input count]; NSString *output = [@"" stringByPaddingToLength:(2*count-1) withString:@"?," startingAtIndex:0]; // Result: ?,?,? 

stringByPaddingToLength通过附加模式@"?,"字符,将给定的string(本例中为空string)填充到给定的长度。