ios - 带有条件的[NSArray componentsJoinedByString]

时间:2013-07-18 10:45:06

标签: ios nsarray concatenation

我想在某些条件下使用-[NSArray componentsJoinedByString]例如:将我的数组的所有元素连接到“,”除了最后一个我想要“和”的元素。

它会像python一样:

', '.join(array[:-1]) + ' and ' + array[-1]

是否有一种方法或方法可以在一行中完成这一操作,避免所有if else内容?

4 个答案:

答案 0 :(得分:3)

您可以使用subarrayWithRange:stringWithFormat:执行相同的操作。您至少需要1 if来检查数组中的项目数,并确保您没有索引异常。

答案 1 :(得分:2)

尝试这样,我不知道这是否有效,但检查一次,

 NSArray *arr= [[NSArray alloc]initWithObjects:@"1",@"2",@"3", nil];
    NSString *string = [arr componentsJoinedByString:@","];
    NSString *str= [NSString stringWithFormat:@"%@ and %@",[string substringToIndex:[string length]-[[arr lastObject] length]-1],[arr lastObject]];
    NSLog(@"%@",str);

答案 2 :(得分:1)

它可能不是最有效的,但它是一个很好的简单解决方案,可以获取具有字符串表示形式的对象数组,并将它们转换为以逗号分隔的列表,例如1,2,3和4。

@implementation NSArray (MyCollection)

- (NSString *)stringCommaAndSeparated
{
    return [self stringCommaAndSeparatedUsingStringConverter:^NSString *(id object) {
        assert( [object isKindOfClass:NSString.class] );
        return (NSString *)object;
    }];
}

- (NSString *)stringCommaAndSeparatedUsingStringConverter:(NSString *(^)(id object))stringConverter
{
    assert( stringConverter );

    if( self.count == 0 )
        return @"";

    if( self.count == 1 )
        return stringConverter(self.firstObject);

    if( self.count == 2 )
        return [NSString stringWithFormat:NSLocalizedString(@"%@ and %@", nil), stringConverter(self[0]), stringConverter(self[1]) ];

    NSMutableString *string = [[NSMutableString alloc] init];
    for( int index = 0;  index < self.count-1;  index += 1 )
        [string appendFormat:NSLocalizedString(@"%@, ", nil), stringConverter(self[index])];

    [string appendFormat:NSLocalizedString(@"and %@", nil), stringConverter(self.lastObject)];

    return string;  // This is returning a mutable string, but we could copy it to an immutable one!
}

@end

以下是此操作的示例:

        // Results in @"1, 2, 3, and 4"
        NSString *str  = [@[@"1", @"2", @"3", @"4"] stringCommaAndSeparated];

        // Results in @"1, 2, 3, and 4"
        NSString *str2 = [@[@(1), @(2), @(3), @(4)] stringCommaAndSeparatedUsingStringConverter:^NSString *(id object) {
                assert( [object isKindOfClass:NSNumber.class] );
                NSNumber *number = object;
                return number.stringValue;
            }];

答案 3 :(得分:0)

这是我的类别解决方案,基于Wain的回答:

@implementation NSArray (NSString)

- (NSString *)listStringUsingLocale:(NSLocale *)locale
{
    if(!self.count)
        return nil;

    if(!locale)
        locale = [NSLocale currentLocale];

    NSString *language = [locale objectForKey: NSLocaleLanguageCode];

    if([language isEqualToString:@"en"])
    {
        if (self.count > 1)
        {
            NSArray *arr1 = [self subarrayWithRange:NSMakeRange(0, self.count - 1)];
            return [NSString stringWithFormat:@"%@ and %@", [arr1 componentsJoinedByString:@", "], self.lastObject];
        }
        else
        {
            return self[0];
        }
    }

    return nil;
}

@end

我添加了添加基于区域设置选项的选项。