Split string to equal length substrings in Java

后端 未结 21 2336
日久生厌
日久生厌 2020-11-22 02:56

How to split the string \"Thequickbrownfoxjumps\" to substrings of equal size in Java. Eg. \"Thequickbrownfoxjumps\" of 4 equal size should give th

21条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 03:29

    public static String[] split(String input, int length) throws IllegalArgumentException {
    
        if(length == 0 || input == null)
            return new String[0];
    
        int lengthD = length * 2;
    
        int size = input.length();
        if(size == 0)
            return new String[0];
    
        int rep = (int) Math.ceil(size * 1d / length);
    
        ByteArrayInputStream stream = new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_16LE));
    
        String[] out = new String[rep];
        byte[]  buf = new byte[lengthD];
    
        int d = 0;
        for (int i = 0; i < rep; i++) {
    
            try {
                d = stream.read(buf);
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            if(d != lengthD)
            {
                out[i] = new String(buf,0,d, StandardCharsets.UTF_16LE);
                continue;
            }
    
            out[i] = new String(buf, StandardCharsets.UTF_16LE);
        }
        return out;
    }
    

提交回复
热议问题