Java String:Split long String的递归解决方案,用于固定长度的较小部分并将它们组合在一起

时间:2015-01-21 03:16:54

标签: java string recursion

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

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();
}

2 个答案:

答案 0 :(得分:2)

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

/**
 * @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);
    }

}

答案 1 :(得分:-2)

我推荐带有SplitterJoiner类的Guava库。

<强>用法

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