java实现String字符串或数组分成若干包平均分组

简易的将String和数组进行分组方法

String分组

    public static List<String> StringSplit() {
    
    
        
        int packetNum = 9;//分成几组
        
        String str = "123456789012345678901234567890";//要分组的字符串
        
        List<String> list =new ArrayList<String>();
        
        int packetLength = str.length()/packetNum;
        
        for (int i = 0; i < packetNum-1; i++) {
    
    
            
            list.add(str.substring(i*packetLength,  i*packetLength+packetLength));
        }
        
        list.add(str.substring((packetNum-1)*packetLength,  str.length()));
        
        return list;
        
    }

数组分组

    public static List<byte[]> ByteArraySplit() {
    
    
        
        List<byte[]> list =new ArrayList<byte[]>();
        
        int packetNum = 9;//分成几组
        
        byte[] byteArray = new  byte[]{
    
    1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0};//要分组的数组
        
        int packetLength = byteArray.length/packetNum;
         
        for (int i = 0; i < packetNum-1; i++) {
    
    
            
            byte packetByte[] = new byte[packetLength];
            
            System.arraycopy(byteArray, i*packetLength,  packetByte, 0, packetLength);
            
            list.add(packetByte);
        }
        
        byte endPacketByte[] = new  byte[byteArray.length-(packetNum-1)*packetLength];
        
        System.arraycopy(byteArray,  (packetNum-1)*packetLength,endPacketByte, 0,  endPacketByte.length);
        list.add(endPacketByte);
        
        return list;
    }

猜你喜欢

转载自blog.csdn.net/weixin_36998210/article/details/114267328