Do you know a java method to expand the chars of a text into spaces?
My text:
1. <tab> firstpoint <tab> page 1
10. <tab> secondpoint <tab> page 10
If I directly replace the tab by, let say, 4 spaces, I will have
1. firstpoint page1
10. secondpoint page2
Instead of it, I need a method to replace each tab by the number of spaces it really corresponds to (as the command :retab of vim does). Any solution?
I think there might be an issue with the retab() function above ignoring an initial tab. I made my own; hereby placed into public domain.
public static String expandTabs(String s, int tabSize) {
if (s == null) return null;
StringBuilder buf = new StringBuilder();
int col = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.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 String spaces(int n) {
StringBuilder buf = new StringBuilder();
for (int sp = 0; sp < n; sp++) buf.append(" ");
return buf.toString();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With