Indenting Text Documents

Problem

You need to indent (or “undent” or “dedent”) a text document.

Solution

To indent, either generate a fixed-length string and prepend it to each output line, or use a for loop and print the right number of spaces.

// Indent.java
/** the default number of spaces. */
static int nSpaces = 10;

while ((inputLine = is.readLine(  )) != null) {
    for (int i=0; i<nSpaces; i++) System.out.print(' ');
    System.out.println(inputLine);
}

A more efficient approach to generating the spaces might be to construct a long string of spaces and use substring( ) to get the number of spaces you need.

To undent, use substring to generate a string that does not include the leading spaces. Be careful of inputs that are shorter than the amount you are removing! By popular demand, I’ll give you this one too. First, though, here’s a demonstration of an Undent object created with an undent value of 5, meaning remove up to five spaces (but don’t lose other characters in the first five positions).

$ java Undent
Hello World
Hello World
 Hello
Hello
     Hello
Hello
      Hello
 Hello
 
^C
$

I test it by entering the usual test string “Hello World”, which prints fine. Then “Hello” with one space, and the space is deleted. With five spaces, exactly the five spaces go. With six or more spaces, only five spaces go. And a blank line comes out as a blank line (i.e., without throwing an Exception or otherwise going berserk). I think it works!

import java.io.*; /** Undent - remove up to 'n' leading spaces */ public ...

Get Java Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.