将多个数组值组合成一个字符串值?

时间:2016-06-15 05:20:50

标签: objective-c arrays

我想将数组值合并为一个字符串。 我的阵列就像......

 array1=[@"fizan",@"nike",@"pogo"];
 array2=[@"round",@"rectangle",@"square"];
 array3=[@"frame",@"frame",@"frame"];

我需要这样......

value1 = fizan round frame
value2 = nike rectangle frame
value3 = pogo square frame

2 个答案:

答案 0 :(得分:1)

这样做

NSArray *array1 = @[@"fizan", @"nike", @"pogo"];
NSString *value = [array1 componentsJoinedByString:@" "];
NSLog(@"value = %@", value);

输出会像

一样
value = fizan nike pogo

对于你的情况

    NSArray *completeArray = @[@[@"fizan",@"nike",@"pogo"], @[@"round",@"rectangle",@"square"], @[@"frame",@"frame",@"frame"]];

    NSMutableArray *resultArray = [NSMutableArray array];

    unsigned long count = 1;

    for (int i = 0; i< count; i++) {
        NSMutableArray *listArray = [NSMutableArray array];
        for (NSArray *itemArray in completeArray) {
            count = MAX(count,itemArray.count);
            if (i < itemArray.count) {
                [listArray addObject:itemArray[i]];
            }
        }
        [resultArray addObject:listArray];
    }

    for (NSArray *itemArray in resultArray) {
        NSString *value = [itemArray componentsJoinedByString:@" "];
        NSLog(@"value = %@", value);
    }

输出

 value = fizan round frame
 value = nike rectangle frame
 value = pogo square frame

答案 1 :(得分:1)

试试这个:

NSArray *array1= @[@"fizan",@"nike",@"pogo"];
NSArray *array2= @[@"round",@"rectangle",@"square"];
NSArray *array3= @[@"frame",@"frame",@"frame"];
NSMutableArray *array = [[NSMutableArray alloc] initWithArray:@[array1,array2,array3]];
NSMutableArray *output = [[NSMutableArray alloc] init];
NSString *a;
NSInteger count = array.count;

for (int i = 0; i<array1.count; i++) {
    a = @"";
    for (int j = 0; j<count; j++) {
        a = [a isEqualToString: @""] ? [NSString stringWithFormat:@"%@",[[array objectAtIndex:j] objectAtIndex:i]] : [NSString stringWithFormat:@"%@ %@",a,[[array objectAtIndex:j] objectAtIndex:i]];
    }
    [output addObject:a];
}

for (int i = 0; i < output.count; i++) {
    NSLog(@"value %i -> %@",i+1,output[i]);
}

希望这有帮助!

<强>更新

NSArray *array1= @[@"fizan",@"",@"pogo"];
NSArray *array2= @[@"round",@"rectangle",@"square"];
NSArray *array3= @[@"frame",@"frame",@"frame"];

NSMutableArray *array = [[NSMutableArray alloc] initWithArray:@[array1,array2,array3]];
NSMutableArray *output = [[NSMutableArray alloc] init];
NSString *a;
NSInteger count = array.count;

for (int i = 0; i<array1.count; i++) {
    a = @"";
    for (int j = 0; j<count; j++) {
        a = [a isEqualToString: @""] ? [NSString stringWithFormat:@"%@",[[array objectAtIndex:j] objectAtIndex:i]] : [NSString stringWithFormat:@"%@ %@",a,[[array objectAtIndex:j] objectAtIndex:i]];
    }
    [output addObject:a];
}

for (int i = 0; i < output.count; i++) {
    NSLog(@"value %i -> %@",i+1,output[i]);
}

我已经测试了这段代码。它完美无缺。再次检查并重新考虑问题。