Java - Write code to Split a String into multiple sub-strings of equal length.

Requirements

Write code to Split a String into multiple sub-strings of equal length.

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String string = "book2s.com";
        int length = 42;
        System.out/* w  w  w.  j  a va2 s .  c o  m*/
                .println(java.util.Arrays.toString(split(string, length)));
    }

    /**
     * Splits a String into multiple sub-strings of equal length.
     * 
     * @param string
     *            the string to split
     * @param length
     *            the length of the sub-strings
     * @return an array of substrings.
     */
    public static String[] split(String string, int length) {

        if ((string == null) || (length < 1)) {
            return new String[0];
        }
        int l = (int) Math.ceil((double) string.length() / (double) length);
        String[] result = new String[l];

        for (int i = 0; i < l; ++i) {
            try {
                result[i] = string.substring((i * length),
                        ((i * length) + length));
            } catch (StringIndexOutOfBoundsException e) {
                result[i] = string.substring(i * length);
            }
        }

        return result;
    }
}