如何使用 char 数组来拆分字符串,创建一个接收块大小和要考虑的最大大小的通用方法,并返回一个 String 数组?
public class SplitStringIntoFixedSizeChunks {
public static String[] Split(String text, int chunkSize, int maxLength) {
char[] data = text.toCharArray();
int len = Math.min(data.length,maxLength);
String[] result = new String[(len+chunkSize-1)/chunkSize];
int linha = 0;
for (int i=0; i < len; i+=chunkSize) {
result[linha] = new String(data, i, Math.min(chunkSize,len-i));
linha++;
}
return result;
}
public static void main(String[] args) {
String x = "flskdafsld~fdsakçkçfsda sfdaldsak~çfdskkfadsçlkçfldskçlflçfdskçldksçlkfdslçakafdslçdsklçfdskçlafdskçkdfsçlkfds~çlkfasdçlçfdls~kçlf~dksçlsakdçlkfç";
System.out.println("x length: "+x.length());
String[] lines = Split(x, 30, 210);
for (int i=0; i < lines.length; i++) {
System.out.println("lines["+i+"]: (len: "+lines[i].length()+") : "+lines[i]);
}
}
}
此示例结果:
x length: 145
lines[0]: (len: 30) : flskdafsld~fdsakçkçfsda sfdald
lines[1]: (len: 30) : sak~çfdskkfadsçlkçfldskçlflçfd
lines[2]: (len: 30) : skçldksçlkfdslçakafdslçdsklçfd
lines[3]: (len: 30) : skçlafdskçkdfsçlkfds~çlkfasdçl
lines[4]: (len: 25) : çfdls~kçlf~dksçlsakdçlkfç