go to previous page   go to home page   go to next page

Answer:

"Friends,   Romans,   countrymen"

Implementation

Here is the near-complete implementation. The tricky parts with the buffer are not finished. Decide what to do (look at the previous page), then click to see if you are correct.

class FSTtrim
{

  public String transform(String str)
  {
    final char space = ' '; // any char <= space is considered to be white space
    String outString = "";  // the output string. initialize to the empty string.
    String buffer = null;   // buffer for suspected internal white space
    
    int  state = 0;         // the current state
    char current;           // the current character
    int  index = 0 ;        // index of the current character

    if ( str == null ) return null;

    while ( index < str.length()  )
    {
      current = str.charAt( index++ ) ;

      if      ( state==0 && current <= space)
        state = 0;

      else if ( state==0 && current > space )
      {
        state = 1;
        outString += current ;
      }

      else if ( state==1 && current > space )
      {
        state = 1;
        outString += current ;
      }

      else if ( state==1  && current <= space )
      {
        state  = 2;      // start out the buffer
        buffer = "" +  ;   // tricky use of null string
      }

      else if ( state==2  && current <= space )
      {
        state  = 2;
        buffer +=  ;    // append current character to buffer
      }

      else if ( state==2  && current > space )
      {
        state  = 1;      // buffer contains internal white space
        outString +=  ;    // append buffer and current 
      }                             // to outString
    }

  return outString;
  }

}

There is no reject state because there is a transition out of every state for all input characters. On the transition from state 1 to state 2, the buffer is initialized to contain the white space character in current that caused the transition:

buffer = "" + current;

The empty string "" is used so that there is a string object to append the character to.


QUESTION 10:

How many times are new objects created when this method is run?