开发者

Break a String Buffer into 80-character Chunk

开发者 https://www.devze.com 2023-02-27 01:35 出处:网络
I want to crea开发者_C百科te an array of string out of a StringBuffer. I need to break the buffer in every 80 characters. So first string element in the array will contain first 80 characters from the

I want to crea开发者_C百科te an array of string out of a StringBuffer. I need to break the buffer in every 80 characters. So first string element in the array will contain first 80 characters from the buffer, second element will contain the next 80 characters from the buffer. The buffer size may not be divisible by 80. So, the last string element of the array may have the rest which can be less than or equal to 80 characters.

What would be the best way to do that considering that substring function of String might get an index out of bounds exception?


Just make sure you don't ask for too much:

String[] splitBuffer(StringBuffer input, int maxLength)
{
    int elements = (input.length() + maxLength - 1) / maxLength;
    String[] ret = new String[elements];
    for (int i = 0; i < elements; i++)
    {
        int start = i * maxLength;
        ret[i] = input.substring(start, Math.min(input.length(),
                                                 start + maxLength));
    }
    return ret;
}

You may want to consider returning a List<String> instead of a String[], as they're often more convenient to work with.


Or do it the regex way:

public static String[] splitBuffer(CharSequence input, int maxLength) {
    return input.toString().split("(?<=\\G.{" + maxLength + "})");
}

Explanation: \G is a placeholder for the last match


I think that you should use the getChars(int, int, char[], int)


You can use StringUtils.substring(String str, int start, int end) instead of the normal String substring method. This method will never throw an exception.

0

精彩评论

暂无评论...
验证码 换一张
取 消