Thursday, December 13, 2012

For Spliting a String based on given length

// For Spliting a String based on given length and return as a String array
public static String[] splitByLength(String s, int chunkSize) {
    int arraySize = (int) Math.ceil(s.length() / chunkSize);
    if (s.length() % chunkSize != 0) {
        arraySize += 1;
    }
    String[] returnArray = new String[arraySize];
    for (int i = 0; i < returnArray.length; i++) {
        int beginindex = i * chunkSize;
        int endindex = beginindex + chunkSize;
        if (endindex > s.length()) {
            endindex = s.length();
        }
        returnArray[i] = s.substring(beginindex, endindex);
    }
    return returnArray;
}

No comments:

Post a Comment