Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expand the tabs in Java

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?

like image 912
Olivier Faucheux Avatar asked Dec 12 '22 23:12

Olivier Faucheux


1 Answers

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();
}
like image 59
Terence Parr Avatar answered Dec 26 '22 12:12

Terence Parr