Olivier Faucheux Olivier Faucheux - 1 year ago 75
Java Question

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?

Answer Source

Although there's probably a library out there that does this, the manual solution is quite simple:

  1. Create an output buffer (StringBuilder).
  2. Iterate through the string's characters
  3. For each character check if it's a tab or not.
    a. If it's not a tab, add it to the output buffer.
    b. If it's a tab, add a space first, then as many spaces as it takes for the length of the output buffer to be divisible by 4. (Your tab length.)
  4. Return the output buffer.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download