user3850
user3850

Reputation:

How to join NSArray elements into an NSString?

Given an NSArray of NSStrings, is there a quick way to join them together into a single NSString (with a Separator)?

Upvotes: 127

Views: 51811

Answers (3)

Ben G
Ben G

Reputation: 3975

There's also this variant, if your original array contains Key-Value objects from which you only want to pick one property (that can be serialized as a string ):

@implementation NSArray (itertools)

-(NSMutableString *)stringByJoiningOnProperty:(NSString *)property separator:(NSString *)separator
{
    NSMutableString *res = [@"" mutableCopy];
    BOOL firstTime = YES;
    for (NSObject *obj in self)
    {
        if (!firstTime) {
            [res appendString:separator];
        }
        else{
            firstTime = NO;
        }
        id val = [obj valueForKey:property];
        if ([val isKindOfClass:[NSString class]])
        {
            [res appendString:val];
        }
        else
        {
            [res appendString:[val stringValue]];
        }
    }
    return res;
}


@end

Upvotes: 1

BJ Homer
BJ Homer

Reputation: 49034

-componentsJoinedByString: on NSArray should do the trick.

Upvotes: 12

Dave DeLong
Dave DeLong

Reputation: 243156

NSArray * stuff = /* ... */;
NSString * combinedStuff = [stuff componentsJoinedByString:@"separator"];

This is the inverse of -[NSString componentsSeparatedByString:].

Upvotes: 316

Related Questions