将两个一维字符串数组合并为一个带分隔符的数组

我有两个数组:

a = ["a","b","c"]

b = ["d","e","f"]

如何将它们合并到一个数组中,如下所示:

c = ["a=d", "b=e", "c=f"]

使用等号 ( =) 作为合并字符串之间的分隔符?

回答

你可以在循环的帮助下做到这一点,例如

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        String[] a = { "a", "b", "c" };
        String[] b = { "d", "e", "f" };
        String[] result = new String[a.length];
        for (int i = 0; i < Math.min(a.length, b.length); i++) {
            result[i] = a[i] + "=" + b[i];
        }

        System.out.println(Arrays.toString(result));
    }
}

输出:

[a=d, b=e, c=f]

在Oracle 的本教程中了解有关循环的更多信息。

使用IntStream

import java.util.Arrays;
import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args) {
        String[] a = { "a", "b", "c" };
        String[] b = { "d", "e", "f" };
        String[] result = IntStream
                            .range(0, Math.min(a.length, b.length))
                            .mapToObj(i -> a[i] + "=" + b[i])
                            .toArray(String[]::new);
        
        System.out.println(Arrays.toString(result));
    }
}


以上是将两个一维字符串数组合并为一个带分隔符的数组的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>