Reputation: 384
I have an NSArray
of String phrases like @[@"unanswered questions", @"inspection purpose not selected", @"customer name empty"]
.
I would like to combine these strings in to a comma separated string with the word @"and"
coming between the last two items.
NSArray
componentsJoinedByString
will join with commas, but won't put in the @" and "
.
Is there an easy way to do this?
Upvotes: 1
Views: 180
Reputation: 384
Here's davide rosetto's answer but using a mutable string:
NSArray *array = @[@"unanswered questions", @"inspection purpose not selected", @"customer name empty"];
NSMutableString *str = [NSMutableString stringWithString:array[0]];
if (array.count > 1) {
for (int i = 1; i < array.count - 1; i++) {
[str appendFormat:@", %@", array[i]];
}
[str appendFormat:@" and %@", array.lastObject];
}
NSLog(@"%@", str);
Upvotes: 0
Reputation: 384
Here's what I ended up doing.
+ (NSString*)joinStringArrayWithAnd:(NSArray*)strings
{
if (strings.count > 1) {
NSMutableArray *mutableStrings = [strings mutableCopy];
mutableStrings[strings.count - 1] = [NSString stringWithFormat:@"and %@", strings[strings.count - 1]];
strings = mutableStrings;
}
return [strings componentsJoinedByString:@", "];
}
Upvotes: 1
Reputation: 485
Try this:
NSArray *array = @[@"unanswered questions", @"inspection purpose not selected", @"customer name empty"];
NSString *str = array[0];
if (array.count > 1)
for (int i=1; i<array.count-1 ;i++) {
str = [NSString stringWithFormat:@"%@, %@",str,array[i]];
}
str = [NSString stringWithFormat:@"%@ and %@",str,array.lastObject];
}
NSLog(@"%@",str);
Upvotes: 1
Reputation: 4315
A more flexible solution would be to iterate over each NSString in your array and append it to the final string:
NSString *finalString = @"";
//Iterate over the strings from your array
for (int i=0; i<[yourArray count]; i++) {
if(i != yourArray.count-1)
finalString = [finalString stringByAppendingString:[NSString stringWithFormat:@"%@, ", yourArray[i]]];
else
finalString = [finalString stringByAppendingString:[NSString stringWithFormat:@"and %@", yourArray[i]]];
}
Upvotes: 0
Reputation: 7145
Call componentsJoinedByString
to get your comma separated strings, then string-replace the last comma with @" and "
Upvotes: 0
Reputation: 197
Is the count of items in the array always fixed? If so, you could do it with something like:
NSString *combined = [NSString stringWithFormat: @"%@, %@ and %@", phrases[0], phrases[1], phrases[2]];
-ken
Upvotes: -1