[英]Convert string array to jagged array in java
我有一個一維值數組,我需要使用鋸齒形數組將這些值分成幾組來進行一系列計算。 例如
int array []={1 2 3 4 5 6 7 8 9 10}
我想分離並分配一個數組中的前4個,再分配另一個數組中的3個,然后分配第三個數組中的最后3個。 我希望在我的代碼中得到這樣的輸出。
int [][] x = new int [3][];
x[0] = new int [4];
x[0] = {1 2 3 4};
x[1] = new int [3];
x[1] = {5 6 7};
x[2] = new int [3];
x[2] = {8 9 10};
還有什么其他方法可以通過使用靈活的for循環來制作這個鋸齒狀的數組,並且我可以將此數組拆分為M個組或N個值組嗎? 我嘗試使用substring()訪問這些值,但是我不確定如何繼續進行下去,或者我是否做對了。
for( int i=0; i<x.length; i++) {
x [i]= array.substring (0,3);
x [i]=array.substring (4,6);
x [i]=array.substring(7,9);
}
我只是編程的新手,但是這段代碼顯然是錯誤的,但是請您能幫助我嗎? 謝謝。
x[0] = new int[4];
System.arraycopy(array, 0, x[0], 0, 4);
x[1] = new int[3];
System.arraycopy(array, 4, x[1], 0, 3);
x[2] = new int[3];
System.arraycopy(array, 7, x[2], 0, 3);
如果沒有,您的問題可能會引起誤解。 子陣列的大小應從何而來?
還是更多您想要的?
int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int xLength = 3;
int[][] x = new int[xLength][];
int arrayLength = array.length;
int remainders = arrayLength % xLength;
int subArrayLength = arrayLength / xLength;
int arrayIndex = 0;
for (int i = 0; i < arrayLength; i++)
{
int adjustedSubArrayLength = subArrayLength;
if (remainders > 0)
{
adjustedSubArrayLength++;
remainders--;
}
x[i] = new int[adjustedSubArrayLength];
System.arraycopy(array, arrayIndex, x[i], 0, adjustedSubArrayLength);
arrayIndex = adjustedSubArrayLength;
}
因此,在Java中創建數組后就無法更改其大小,需要新的數組來存儲數據。 有一個靜態的System
函數,它允許您復制特定長度的數組,該數組稱為: System.arraycopy(src, srcPos, dest, destPos, length)
嘗試這個。
static int[][] to2dArray(int[] array, int... colSizes) {
int[][] result = new int[colSizes.length][];
for (int i = 0, start = 0; i < colSizes.length; start += colSizes[i++])
result[i] = Arrays.copyOfRange(array, start, start + colSizes[i]);
return result;
}
和
int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
System.out.println(Arrays.deepToString(to2dArray(array, 4, 3, 3)));
// -> [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.