如何在Java中混合两种阵列? [英] How to mix two arrays in Java?

查看:140
本文介绍了如何在Java中混合两种阵列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些的String []数组,例如:

  ['A1','A2']
['B1','B2','B3','B4']
['C1']

如何搭配他们,让我得到 [A1,B1,C1,A2,B2,B3,B4'] (0的元素,则b,C,A,b,C的1元等等)?谢谢

更准确地说所得阵列必须包括第一阵列的第一值,则第二阵列的所述第一值的,......,最后一个阵列的第一值,所述第一阵列的第二值,..中,最后阵列的第二值,...,最大阵列的最后一个值。如果数组的大小相同的不是,则较小的只是没有被考虑在内。

下面是一个例子:

  A1 A2 A3 A4
B1,B2,B3 B4 B5 B6 B7
C1 C2
D1 D2 D3 D4 D5组合为(括号只是突出的步骤,所以他们真正的意思是什么):
(A1 B1 C1 D1)(A2 B2 C2 D2)(A3 B3 D3)和(a4 B4 D4)(B5 D5)(B6)(B7)

另外,我想可变数量的阵列组合,而不仅仅是3或4


解决方案

 字符串结果[] =新的String [则为a.length + b.length个+ c.length];
的for(int i = 0,J = 0; J< result.length ++我){
    如果(ⅰ&下;则为a.length){
        结果[J ++] = a [i];
    }
    如果(I< b.length个){
        结果[J ++] = B [I]
    }
    如果(ⅰ&下; c.length){
        结果[J ++] = C [I]
    }
}

更新:更普遍

 的String []合并(的String []数组...){
    INT长度= 0;
    对于(字符串[]答:数组){
        长度+ =则为a.length;
    }
    字符串结果[] =新的String [长度]
    的for(int i = 0,J = 0; J<长度; ++ I){
        对于(字符串[]答:数组){
            如果(ⅰ&下;则为a.length){
                结果[J ++] = a [i];
            }
        }
    }
    返回结果;
}

I have some String[] arrays, for example:

['a1', 'a2']
['b1', 'b2', 'b3', 'b4']
['c1']

How can I mix them, so that I get ['a1', 'b1', 'c1', 'a2', 'b2', 'b3', 'b4'] (0 element of a, then b, c, 1 element of a, b, c and so on)? Thanks

More accurately the resulting array must consist of the first value of the first array, then the first value of the second array, ..., the first value of the last array, the second value of the first array, ..., the second value of the last array, ..., the last value of the biggest array. If arrays are not of the same size, the smaller ones just aren't being taken into account.

Here's an illustration:

a1 a2 a3 a4
b1 b2 b3 b4 b5 b6 b7
c1 c2
d1 d2 d3 d4 d5

Combines into (brackets are just to highlight steps, so they really mean nothing):
(a1 b1 c1 d1) (a2 b2 c2 d2) (a3 b3 d3) (a4 b4 d4) (b5 d5) (b6) (b7)

Also, I'd like to combine variable number of array, not just 3 or 4

解决方案

String result[] = new String[a.length+b.length+c.length];
for (int i = 0, j = 0; j < result.length; ++i) {
    if (i < a.length) {
        result[j++] = a[i];
    }
    if (i < b.length) {
        result[j++] = b[i];
    }
    if (i < c.length) {
        result[j++] = c[i];
    }
}

UPDATE: more generally

String[] merge(String[]... arrays) {
    int length = 0;
    for (String[] a: arrays) {
        length += a.length;
    }
    String result[] = new String[length];
    for (int i = 0, j = 0; j < length; ++i) {
        for (String[] a: arrays) {
            if (i < a.length) {
                result[j++] = a[i];
            }
        }
    }
    return result;
}

这篇关于如何在Java中混合两种阵列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆