[英]Java String: Recursion solution for Split long Sting to fixed length smaller parts and combine them
According to UI component requirement, with the use of long String value I have to populate fixed length smaller String values and combine them. 根据UI组件要求,使用长字符串值时,我必须填充固定长度的较小字符串值并将其组合。
Ex:- long String value: AAABBBCCDEEEFFGGGG
Fixed length smaller String value: AAA
BBB
CCD
EEE
FFG
GGG
For make this enable I have write some utility method as follow. 为了启用此功能,我编写了一些实用程序方法,如下所示。 I want to know, as a optimise solution whether it can write some recursion method ?
我想知道,作为一种优化解决方案,是否可以编写一些递归方法? Thanks.
谢谢。
/**
* @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();
}
This worked for me. 这对我有用。 Recursion saves a lot of code.
递归节省了大量代码。
/**
* @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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.