Efficiently create placeholder template NSString with NSArray of values

喜欢而已 提交于 2019-12-13 16:12:14

问题


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.

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

回答1:


What about this?

NSArray *input = @[@(55), @(33), @(12)];

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

stringByPaddingToLength fills the given string (the empty string in this case) to the given length by appending characters from the pattern @"?,".



来源:https://stackoverflow.com/questions/19384072/efficiently-create-placeholder-template-nsstring-with-nsarray-of-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!