Java String: Split long String 到固定长度的更小部分并组合它们的递归解决方案

Java String: Recursion solution for Split long Sting to fixed length smaller parts and combine them

根据UI组件要求,使用长字符串值我必须填充固定长度的较小字符串值并将它们组合起来。

Ex:-  long String value: AAABBBCCDEEEFFGGGG

      Fixed length smaller String value: AAA
                                         BBB
                                         CCD
                                         EEE
                                         FFG
                                         GGG

为了启用此功能,我编写了一些实用方法,如下所示。 我想知道,作为优化解决方案是否可以编写一些递归方法?谢谢。

/**
 * @param fullLongString Long String value
 * @param maxLengthOfPart Maximum length of the smaller String 
 * @return String result as a short String
 */
public static String getShortString(String fullLongString, int maxLengthOfPart) {

    if((fullLongString == null) || (fullLongString.trim().equals("")) || (maxLengthOfPart <= 0) || (fullLongString.length() <= maxLengthOfPart)) {
        return fullLongString;
    }

    StringBuilder fullShortString = new StringBuilder();
    int numberOfStringParts = fullLongString.length() / maxLengthOfPart;

    int startIndex = 0;
    int endIndex = maxLengthOfPart;

    for(int i = 0; i < numberOfStringParts; i++) {

        String smallPart = fullLongString.substring(startIndex, endIndex);

        if(i == 0) {
            fullShortString.append(smallPart);
        } else {
            fullShortString.append("\n").append(smallPart);
        }

        startIndex = endIndex;
        endIndex += maxLengthOfPart;
    }

    String remainPart = fullLongString.substring((endIndex - maxLengthOfPart), (fullLongString.length()));

    if((remainPart != null) && (!remainPart.trim().equals(""))) {
        fullShortString.append("\n").append(remainPart);
    }

    return fullShortString.toString();
}

这对我有用。递归节省大量代码。

/**
 * @param fullLongString Long String value
 * @param maxLengthOfPart Maximum length of the smaller String 
 * @return String result as a short String
 */
public static String getShortString(String fullLongString, int maxLengthOfPart) {

    if((fullLongString == null) || (fullLongString.trim().equals("")) || (maxLengthOfPart <= 0) || (fullLongString.length() <= maxLengthOfPart)) {
        return fullLongString;
    } else {
       String firstPart = fullLongString.substring(0, maxLengthOfPart);
       return firstPart + "\n" + getShortString(fullLongString.substring(maxLengthOfPart, fullLongString.length()),maxLengthOfPart);
    }

}

我推荐 Splitter and a Joiner class.

附带的 Guava 库

用法:

public static String splitEqual(String strand, int width) {
    return Joiner.on('\n').join(Splitter.fixedLength(width).trimResults().split(strand));
}