string 如何将 NSArray 元素连接到 NSString 中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1387440/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 00:31:28  来源:igfitidea点击:

How to join NSArray elements into an NSString?

cocoastring

提问by Dave DeLong

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

给定一个 NSString 的 NSArray,是否有一种快速的方法将它们连接到一个 NSString(带有分隔符)中?

回答by Dave DeLong

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

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

这是 的倒数-[NSString componentsSeparatedByString:]

回答by BJ Homer

-componentsJoinedByString:on NSArray should do the trick.

-componentsJoinedByString:在 NSArray 上应该可以解决问题。

回答by Ben G

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