Saturday, December 24, 2011

Java's character and assorted string classes support text-processing - 24


For another practical illustration of StringBuffer's append(String str) method, as well as StringBuffer(int length), append(char c), and deleteCharAt(int index), I created an Editor application that demonstrates a basic line-oriented text editor:
Listing 5: Editor.java
// Editor.java
import java.io.IOException;
class Editor
{
   public static int MAXLINES = 100;
   static int curline = -1; // Current line.
   static int lastline = -1; // Last appended line index.
   // The following array holds all lines of text. (Maximum is MAXLINES.)
   static StringBuffer [] lines = new StringBuffer [MAXLINES];
   static
   {
      // We assume 80-character lines. But who knows? Because StringBuffers
      // dynamically expand, you could end up with some very long lines.
      for (int i = 0; i < lines.length; i++)
           lines [i] = new StringBuffer (80);
   }
   public static void main (String [] args)
   {
      do
      {
          // Prompt user to enter a command
          System.out.print ("C: ");
          // Obtain the command, and make sure there is no leading/trailing
          // white space
          String cmd = readString ().trim ();
          // Process command
          if (cmd.equalsIgnoreCase ("QUIT"))
              break;
          if (cmd.equalsIgnoreCase ("ADD"))
          {
              if (lastline == MAXLINES - 1)
              {
                  System.out.println ("FULL");
                  continue;
              }
              String line = readString ();
              lines [++lastline].append (line);
              curline = lastline;
              continue;
          }
          if (cmd.equalsIgnoreCase ("DELFCH"))
          {
              if (curline > -1 && lines [curline].length () > 0)
                  lines [curline].deleteCharAt (0);
              continue;
          }
          if (cmd.equalsIgnoreCase ("DUMP"))
              for (int i = 0; i <= lastline; i++)
                   System.out.println (i + ": " + lines [i]);
      }
      while (true);
   }
   static String readString ()
   {
      StringBuffer sb = new StringBuffer (80);
      try
      {
         do
         {
             int ch = System.in.read ();
             if (ch == '\n')
                 break;
             sb.append ((char) ch);
         }
         while (true);
      }
      catch (IOException e)
      {
      }
      return sb.toString ();
   }
}

To see how Editor works, type java Editor. Here is one example of this program's output:
C: add
some text
C: dump
0: some text
C: delfch
C: dump
0: ome text
C: quit

No comments: