比方说你有一个字符串,像这样
String[][] array= new String[][]
{
{"a","b","c"},
{"d","e","f"},
{"h","i","j"},
{"k","l","m"}
};
一个二维数组,现在你需要一种方法来这些阵列在中途点分割。让我们得到中间点。找出阵列有多大,然后将其减半。请注意,如果数组长度不是偶数,也必须处理。例如,长度为3.如果是这种情况,我们将使用Math.floor()函数。
int arrayLength = array.length;
int halfWayPoint = Math.floor(arrayLength/2);
//we also need to know howmany elements are in the array
int numberOfElementsInArray = array[0].length;
现在我们有了所有的信息来创建两个二维数组。现在我们必须明确地复制创建和复制数据。
//the length of the first array will be the half way point which we already have
String [][] newArrayA = new String[halfWayPoint][numberOfElementsInArray];
//this copies the data over
for(int i = 0; i < halfWayPoint; i++)
{
newArrayA[i] = array[i];
}
//now create the other array
int newArrayBLength = array.length - halfWayPoint;
String[][] newArrayB = new String[newArrayBLength][numberOfElementsInArray];
/*
* This copies the data over. Notice that the for loop starts a halfWayPoint.
* This is because this is where we left of copying in the first array.
*/
for(int i = halfWayPoint; i < array.length; i++)
{
newArrayB[i] = array[i];
}
而你的成就!现在
,如果你想这样做更好一点,你可以做这样的
int half = Math.floor(array/2);
int numberOfElementsInArray = array[0].length;
String [][] A = new String[half][numberOfElementsInArray];
String [][] B = new String[array.length - half][numberOfElementsInArray];
for(int i = 0; i < array.length; i++)
{
if(i < half)
{
A[i] = array[i];
}
else
{
B[i] = array[i];
}
}
最后,如果你不想明确做到这一点,你可以使用内置的功能。 System.arraycopy()就是一个例子。这是一个链接到它的api System.arraycopy()
int half = Math.floor(array/2);
int numberOfElementsInArray = array[0].length;
String [][] A = new String[half][numberOfElementsInArray];
String [][] B = new String[array.length - half][numberOfElementsInArray];
System.arraycopy(array,0,A,0,half);
System.arraycopy(array,half,B,0,array.length - half);