How to join NSArray elements into an NSString?

后端 未结 3 1112
陌清茗
陌清茗 2021-01-29 23:18

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

相关标签:
3条回答
  • 2021-01-29 23:58
    NSArray * stuff = /* ... */;
    NSString * combinedStuff = [stuff componentsJoinedByString:@"separator"];
    

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

    0 讨论(0)
  • 2021-01-29 23:58

    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
    
    0 讨论(0)
  • 2021-01-30 00:05

    -componentsJoinedByString: on NSArray should do the trick.

    0 讨论(0)
提交回复
热议问题