连接指定数量的字符串:
/**
* 用指定的分隔符连接指定数量的字符串并存放在buffer中<br>
* 由指定连接个数字符串进行连接后的总字符长度为:(str.length()+separator.length())*num<br>
* 如果tempBuffer.length()小于连接后的总字符长度时即循环添加自身,这样连接个数将会以2的指数增长<br>
* 反之,如果小于总字符长度时,则求出剩余连接个数递归调用该方法自身<br>
*
* @param str
* 被连接字符串
* @param num
* 需连接的个数
* @param buffer
* 存放连接后的字符串
*/
public static void concatNumberOfStrBySeparator(String str, String separator, int num,
StringBuffer buffer) {
if (num < 1 || buffer == null) {
buffer.append(separator);
return;
}
StringBuffer tempBuffer = new StringBuffer(256);
tempBuffer.append(separator + str);
int totalLength = (str.length()+separator.length())*num;
while (tempBuffer.length()*2 < totalLength) {
tempBuffer.append(tempBuffer);
}
int remainLength = num - tempBuffer.length() / 2;
buffer.append(tempBuffer);
tempBuffer = null; // 不用了的对像置空能节约不少内存
if (remainLength > 0) {
concatNumberOfStrBySeparator(str, separator, remainLength, buffer);
}
}
测试代码:
public static void main(String[] args) {
StringBuffer buffer = new StringBuffer();
concatNumberOfStrBySeparator("?", ",", 10, buffer);
System.out.println(buffer.toString().substring(1));
}