// Collection of code snippets by Arne VajhÃ¸j 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

public class SmartSplit {
    public static List<List<Byte>> split1(String s, int maxlen) throws UnsupportedEncodingException {
        List<List<Byte>> res = new ArrayList<List<Byte>>();
        int ix = 0;
        while(ix < s.length()) {
            int d = Math.min(s.length() - ix, maxlen);
            byte[] ba = s.substring(ix, ix + d).getBytes("UTF-8");
            List<Byte> tmp = new ArrayList<Byte>();
            for(byte b : ba) {
                tmp.add(b);
            }
            res.add(tmp);
            ix += d;
        }
        return res;
    }
    public static List<List<Byte>> split2(String s, int maxlen) throws UnsupportedEncodingException {
        List<List<Byte>> res = new ArrayList<List<Byte>>();
        byte[] ba = s.getBytes("UTF-8");
        int ix = 0;
        while(ix < ba.length) {
            int d = Math.min(ba.length - ix, maxlen);
            List<Byte> tmp = new ArrayList<Byte>();
            for(int i = 0; i < d; i++) {
                tmp.add(ba[ix + i]);
            }
            res.add(tmp);
            ix += d;
        }
        return res;
    }
    public static List<List<Byte>> split3(String s, int maxlen) throws UnsupportedEncodingException {
        List<List<Byte>> res = new ArrayList<List<Byte>>();
        List<Byte> tmp = new ArrayList<Byte>();
        for(int i = 0; i < s.length(); i++) {
            byte[] ba = s.substring(i, i + 1).getBytes("UTF-8");
            if(tmp.size() + ba.length > maxlen) {
                res.add(tmp);
                tmp = new ArrayList<Byte>();
            }
            for(byte b : ba) {
                tmp.add(b);
            }
        }
        if(tmp.size() > 0) {
            res.add(tmp);
        }
        return res;
    }
    public static void main(String[] args) throws UnsupportedEncodingException {
        String s = "ØØØØØ";
        System.out.println("char split:");
        List<List<Byte>> p1 = split1(s, 3);
        for(List<Byte> lst : p1) {
            for(byte b : lst) {
                System.out.print(" " + b);
            }
            System.out.println();
        }
        System.out.println("byte split:");
        List<List<Byte>> p2 = split2(s, 3);
        for(List<Byte> lst : p2) {
            for(byte b : lst) {
                System.out.print(" " + b);
            }
            System.out.println();
        }
        System.out.println("char byte split:");
        List<List<Byte>> p3 = split3(s, 3);
        for(List<Byte> lst : p3) {
            for(byte b : lst) {
                System.out.print(" " + b);
            }
            System.out.println();
        }
    }
}
