Eldar(Abusalimov,Terence Parr)帖子的变体。
更改:
1. 将 if 语句拆分为两行,以便您可以在主体上设置断点
2. 使用 StringBuffer 的容量构造函数来帮助它预先分配存储空间。
public static String expandTabs(String str, int tabSize) {
if (str == null)
return null;
StringBuilder buf = new StringBuilder(str.length()+tabSize);
int col = 0;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
switch (c) {
case '\n' :
col = 0;
buf.append(c);
break;
case '\t' :
buf.append(spaces(tabSize - col % tabSize));
col += tabSize - col % tabSize;
break;
default :
col++;
buf.append(c);
break;
}
}
return buf.toString();
}
public static StringBuilder spaces(int n) {
StringBuilder buf = new StringBuilder(n);
for (int sp = 0; sp < n; sp++)
buf.append(" ");
return buf;
}