String string="0123456789abcd";

StringBuilder str = new StringBuilder(string.replace(" ",""));

    int i = str.length() / 4;
    int j = str.length() % 4;

    for (int x = (j == 0 ? i - 1 : i); x > 0; x--) {
        str = str.insert(x * 4," ");
    }

System.out.println(str);