Google Analytics

Thursday, September 25, 2014

JAVA String Splitting for given length

Observed the code from:
http://stackoverflow.com/questions/12295711/split-a-string-at-every-nth-position

public String[] splitStringEvery(String s, int interval) {
    int arrayLength = (int) Math.ceil(((s.length() / (double)interval)));
    String[] result = new String[arrayLength];

    int j = 0;
    int lastIndex = result.length - 1;
    for (int i = 0; i < lastIndex; i++) {
        result[i] = s.substring(j, j + interval);
        j += interval;
    } //Add the last bit
    result[lastIndex] = s.substring(j);

    return result;
}

No comments:

Post a Comment