Re: [J2SE] String padding 的問題
※ 引述《godfat (godfat 真常)》之銘言:
: : 推 ClareQ:還可以更快喔,照理說不用每次都產生一組char陣列^^ 04/27 02
: 試了一下,這樣確實更快:
: 1 是我原本的寫法
: 2 是原 po 的寫法
: 3 是 infinitlee 的 String.format(為什麼那麼慢?我以為會很快)
: 4 是改成暴力寫死的寫法
哈 我的意思不是要暴力把char[]寫死,
而是嘗試從需求面的角度開發這個class。
通常用到String Padding功能,是為了建立純文字的表格,
特性是每個欄位的長度會一直套用到下一列,
不會不斷產生隨機的padding長度。
在這樣的需求下,
在建構子時就決定要多長,用什麼字元填充,
應該可以獲得最好的使用經驗。
且若在每個欄位重複使用產生出的object,
可以獲得最好的效率。
pad方法傳出char[]是因為在這樣的需求下,
往往會用StringBuffer或是BufferedWriter來承接處理過的內容,
多加上一層String殼反而浪費。
public class StringPadder {
private char[] buf;
private int len;
public StringPadder(int size) {
this(size, ' ');
}
public StringPadder(int size, char ch) {
buf = new char[len = size];
while (--size >= 0) buf[size] = ch;
}
public char[] padRight(String str) { // for text
char[] tmp = new char[len];
int size = str.length();
if (size >= len) size = len;
else System.arraycopy(buf, 0, tmp, size, len - size);
str.getChars(0, size, tmp, 0);
return tmp;
}
public char[] padLeft(String str) { //for number
char[] tmp = new char[len];
int size = str.length(), offset = len - size;
if (offset <= 0) str.getChars(-offset, size, tmp, 0);
else {
System.arraycopy(buf, 0, tmp, 0, offset);
str.getChars(0, size, tmp, offset);
}
return tmp;
}
}
使用範例:
public static void main(String[] args) {
int[] columnSize = new int[] {300, 400, 500, 600, 700};
int n = columnSize.length, testCount = 100000;
char padChar = '.';
String data = "1234567890123456789012345678901234567890";
long t = System.currentTimeMillis();
//每個column建立一個StringPadder
StringPadder[] columns = new StringPadder[n];
for (int i = 0; i < n; i++) columns[i] =
new StringPadder(columnSize[i], padChar);
//產生每列的資料
for (int i = 0; i < testCount; i++)
for (int j = 0; j < n; j++) columns[j].padRight(data);
System.out.println(System.currentTimeMillis() - t);
}
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 118.169.100.236
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 9 之 9 篇):