如何在Java中混合两个数组? [英] How to mix two arrays in Java?

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

问题描述

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

I have some String[] arrays, for example:

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

如何混合它们,以便得到 ['a1', 'b1', 'c1', 'a2', 'b2', 'b3', 'b4'] (a 的 0 个元素,然后是 b、c,a、b、c 的 1 个元素等等)?谢谢

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.

这是一个说明:

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)

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

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];
    }
}

更新:更一般的

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天全站免登陆