使用值的 NSArray 有效地创建占位符模板 NSString [英] Efficiently create placeholder template NSString with NSArray of values
本文介绍了使用值的 NSArray 有效地创建占位符模板 NSString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试为 FMDB 制作一个实用方法,该方法将采用 NSArray 值并返回一串占位符,以根据数组中的值数量在 IN 语句中使用.
I am trying to make a utility method for FMDB which will take an NSArray of values and return a string of placeholders for use in an IN statement based on the number of values in the array.
我想不出一种优雅的方式来创建这个字符串,我是不是缺少一些 NSString 实用方法:
I can't think of an elegant way of creating this string, am I missing some NSString utility method:
// 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
填充给定的字符串(在本例中为空字符串)通过从模式 @"?,"
附加字符到给定的长度.
stringByPaddingToLength
fills the given string (the empty string in this case)
to the given length by appending characters from the pattern @"?,"
.
这篇关于使用值的 NSArray 有效地创建占位符模板 NSString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文