简体   繁体   English

来自两个不同数组的JAVA数组串联

[英]JAVA array concatenation from two different arrays

How to concatenate each and every number from 2 arrays and then give the output individually of the new no. 如何连接2个数组中的每个数字,然后分别给出新编号的输出。 formed? 形成了?

Example: 例:

arr1[1,2,3] 
arr2[2,3,5] 
output: [12,13,15,22,23,25,32,33,33,35]

Here's another way of doing it that doesn't involve using String . 这是另一种不使用String

public static void main(String[] args)
{
    int[] arr1 = { 1, 2, 3 };
    int[] arr2 = { 2, 3, 5 };
    int[] arr = concat(arr1, arr2);     
    System.out.println(Arrays.toString(arr));
}

static int[] concat(int[] arr1, int[] arr2)
{
    int i = 0;
    int[] arr = new int[arr1.length * arr2.length];
    for (int n2 : arr2)
    {
        int pow10 = (int) Math.pow(10, nDigits(n2));
        for (int n1 : arr1)
        {
            arr[i++] = n1 * pow10 + n2;
        }
    }
    return arr;
}

static int nDigits(int n)
{
    return (n == 0) ? 1 : 1 + (int) Math.log10(n);
}

Output: 输出:

[12, 22, 32, 13, 23, 33, 15, 25, 35]

Use a for loop inside of a for loop. for循环内使用for循环。 Then concatenate the item from arr and the item from arr2 . 然后将arr的项目和arr2的项目连接起来。 I used an ArrayList but you could use a normal array if you know the resultant length of the array. 我使用了ArrayList但是如果您知道数组的结果长度,则可以使用普通数组。

    String[] arr = new String[]{"1", "2", "3"};
    String[] arr2 = new String[]{"2", "3", "5"};
    List<String> res = new ArrayList<>();

    for (int i = 0; i < arr.length; i++){
        for (int j = 0; j < arr2.length; j++) {
            res.add(arr[i] + arr2[j]);
        }
    }

    System.out.println(res.toString());

The result is: 结果是:

[12, 13, 15, 22, 23, 25, 32, 33, 35]

If you just want to display the contents of the two array in the form you have given above you can always try doing this instead of concatinating it. 如果您只想以上面给出的形式显示两个数组的内容,则可以始终尝试执行此操作,而不是对其进行概括。

public class ArrayQuestion {
public static void main(String[] args) {
    int arr1[] = {1,2,3};
    int arr2[] = {2,3,5};
    for(int i=0;i<arr1.length;i++) {
        for(int j=0;j<arr2.length;j++) {
            System.out.print(arr1[i]);
            System.out.print(arr2[j]);
            System.out.println();
        }
    }

}

} }

Output : 12 13 15 22 23 25 32 33 35 输出: 12 13 15 22 23 25 32 33 35

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM