Java Indenting Text Documents - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript Java Indenting Text Documents - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Thursday, December 27, 2018

Java Indenting Text Documents

Java 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. 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 class Undent {
 /** the maximum number of spaces to remove. */
 protected int nSpaces;
 Undent(int n) {
 nSpaces = n;
 }
 public static void main(String[] av) {
 Undent c = new Undent(5);
 switch(av.length) {
 case 0: c.process(new BufferedReader(
 new InputStreamReader(System.in))); break;
 default:
 for (int i=0; i<av.length; i++)
 try {
c.process(new BufferedReader(new FileReader(av[i])));
 } catch (FileNotFoundException e) {
 System.err.println(e);
 }
 }
 }
 /** process one file, given an open BufferedReader */
 public void process(BufferedReader is) {
 try {
 String inputLine;
 while ((inputLine = is.readLine( )) != null) {
 int toRemove = 0;
 for (int i=0; i<nSpaces && i < inputLine.length( ); i++)
 if (Character.isSpace(inputLine.charAt(i)))
 ++toRemove;
 System.out.println(inputLine.substring(toRemove));
 }
 is.close( );
 } catch (IOException e) {
 System.out.println("IOException: " + e);
 }
 }
}

No comments:

Post a Comment

Post Top Ad