// 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) 
public class FormatWidth2 {
    public static String printFormatWidth(String s, int w) {
        StringBuilder res = new StringBuilder();
        String tmp = s;
        while(tmp.length() > 0) {
            if(tmp.length() <= w) {
                res.append(tmp);
                tmp = "";
            } else {
                int ix = w - 1;
                while(ix >= 0 && tmp.charAt(ix) != ' ') ix--;
                res.append(tmp.substring(0, ix));
                res.append("\r\n");
                tmp = tmp.substring(ix + 1);
            }
        }
        return res.toString();
    }
    public static void main(String[] args) {
        String s = "Dette er en lille test, hvor vi splitter en sætning.";
        System.out.println(printFormatWidth(s, 15));
        System.out.println(printFormatWidth(s, 20));
        System.out.println(printFormatWidth(s, 25));
        System.out.println(printFormatWidth(s, 30));
    }
}
