递归进行字符串截取:
要求:字符串长度最大不超过256个字符.现在要将此字符串分拆成四段。每段最大不超过64个字符。如果第64个字符不是空格符,则从第64个字符往前找,找到的第一个空格符,并把0-该空格符位置间的子串截取,做为第一段;
然后对剩下的字符串采用类似的操作。
代码:
package com.gobusiness.common.util;
public class DescUtil {
//the N control the line you want to create
public static final int N = 4;
private String [] strArray = null;
public DescUtil(String [] strArray){
this.strArray = strArray;
}
public void setStrArray(String[] strArray) {
this.strArray = strArray;
}
public String[] getStrArray() {
return strArray;
}
public int getArrayLen(){
return this.strArray.length;
}
public void initArray(String strDesc, int i) {
String str = "";
String strTemp = "";
strDesc = strDesc.trim();
if(i == this.getArrayLen()){
return;
}
if(strDesc.length()<=64){
str = strDesc;
strArray[i] = str;
return;
}
if(strDesc.charAt(63)==' '){
str = strDesc.substring(0, 63);
strTemp = strDesc.substring(64);
initArray(strTemp,i+1);
}else{
strTemp = strDesc.substring(0, 64);
int M2 = strTemp.lastIndexOf(" ");
if(M2 == -1){
str = strDesc.substring(0, 64);
strTemp = strDesc.substring(64);
initArray(strTemp,i+1);
}else{
str = strDesc.substring(0, M2);
strTemp = strDesc.substring(M2+1);
initArray(strTemp,i+1);
}
}
if(strArray[i]==null);{
strArray[i] = str;
}
}
}
我把每次截取的子串放在数组的元素中。。
示例结果:
测试代码:
String DescriptionOfCommodity = "";
String DescriptionOfCommodity1 = "";
String DescriptionOfCommodity2 = "";
String DescriptionOfCommodity3 = "";
DescriptionOfCommodity = "111111112222222333333";
String[] strArray = new String[DescUtil.N];
DescUtil descUtil = new DescUtil(strArray);
descUtil.initArray(DescriptionOfCommodity,0);
strArray = descUtil.getStrArray();
if(strArray!=null){
DescriptionOfCommodity = CommonUtil.null2String(strArray[0]);
DescriptionOfCommodity1 = CommonUtil.null2String(strArray[1]);
DescriptionOfCommodity2 = CommonUtil.null2String(strArray[2]);
DescriptionOfCommodity3 = CommonUtil.null2String(strArray[3]);
}
在类中数组的长度来控制进行分拆的行数