问题
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