【问题标题】:How to split the array into multiple如何将数组拆分为多个
【发布时间】:2017-03-23 09:26:51
【问题描述】:

我想将数组拆分为多个较小的数组。下面是我用于获取数组值的代码。

itemtbldata = itemtbldata.substring(1, itemtbldata.length()-1);
System.out.println("itemtbldata   "+itemtbldata);
String[] itemcell = itemtbldata.split(",");
System.out.println(itemcell.length);

例如 itemcell 具有以下值

itemcell = [renu,1252,ed,dev,kalam,8562,ed,dev]

现在我想得到如下。请有人帮忙

arr1 = [renu,1252,ed,dev]
arr2 = [kalam,8562,ed,dev]

【问题讨论】:

  • 你的意思是['renu',1252,'ed','dev','kalam',8562,'ed','dev']
  • 也许他想将一个数组分成两次:-?
  • java vs javascript。它看起来更像 java。
  • @Alexandru-IonutMihai:不精确两次,我想要基于大小。在这种情况下它是 4。所以如果我的 itemcell 的长度为 40。我需要十个数组,每个数组的大小为 4。
  • Java array slicing的可能重复

标签: java arrays


【解决方案1】:

您可以像这样使用System.arraycopy(参见工作演示http://rextester.com/RZA81274

int finalRowSize = 4; //Set here the chunks size
String[] itemcell = {"renu","1252","ed","dev","kalam","8562","ed","dev"};
String[][] result =  monoToBidi(itemcell,itemcell.length / finalRowSize, finalRowSize); 

public static String[][] monoToBidi(final String[] array, final int rows, final int cols){        
        String[][] bidi = new String[rows][cols];
        for ( int i = 0; i < rows; i++ )
            System.arraycopy(array, (i*cols), bidi[i], 0, cols);        
        return bidi;
}

【讨论】:

    【解决方案2】:

    这里是手动编写的Java方法:

    public static void main(String[] args)
    {
        int max = 4;
        String[] data = { "renu", "1252", "ed", "dev", "kalam", "8562", "ed", "dev", "hi", };
    
        // use ceiling so 9 / 4 = 3. (round shouldn't be necessary, but just for safety, here it is)
        int numOfArrays = (int)Math.round(Math.ceil(data.length / (float)max));
        String[][] data2 = new String[numOfArrays][];
    
        // loop over all instances except the last one (as that one might be smaller than the max
        for (int i = 0; i < numOfArrays-1; i++)
        {
            data2[i] = new String[max];
            System.arraycopy(data, i*max, data2[i], 0, max);
        }
        if (numOfArrays > 0)
        {
            int index = numOfArrays-1;
            int length = data.length % max;
            data2[index] = new String[length];
            System.arraycopy(data, index*max, data2[index], 0, length);
        }
    
        System.out.println(Arrays.deepToString(data2));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-16
      • 1970-01-01
      • 1970-01-01
      • 2013-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多