Skip to content
Advertisement

Converting a 1D array to a 2D array

Got an array:

String[] array = song.split("");
[W, U, B, W, U, B, A, B, C, W, U, B]

I need to convert it in two dimension:

String[][] arr = new String[4][3];
[[W, U, B], [W, U, B], [A, B, C], [W, U, B]]

Below code:

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

gives the result:

[[W, U, B], [W, U, B], [W, U, B], [W, U, B]]

How to get:

[[W, U, B], [W, U, B], [A, B, C], [W, U, B]]

Advertisement

Answer

You’re assigning the wrong value to arr[i][j]:

for (int i = 0; i <arr.length ; i++) {
    for (int j = 0; j <arr[j].length ; j++) {
        arr[i][j] = array[i * arr[j].length + j];
    }
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement