How many times are new objects created when this method is run?
A new object is created for every character in the output string, plus some additional objects are created to implement the buffer.
Since String objects are immutable, a new object is created each
time the append operator (+) is used.
Object creation is expensive in terms of
computer time; you may want to avoid it.
You could use the StringBuffer class in
this situation because you can add characters
to it without creating new objects.
You may wish to do this as an exercise.
(But StringBuffer is not part of the AP Computer Science A test.)
Here is the complete program, suitable for running:
class FSTtrimTester
{
public static void main (String[] args)
{
String inString = null;
String outString = null;
FSTtrim fst = new FSTtrim();
inString = args[0];
System.out.println("The trimed string-->" + outString + "<--");
else
System.out.println("Missing input string.");
}
}
class FSTtrim
{
public String transform(String str)
{
final char space = ' '; // any char <= space is white space
String outString = ""; // the string consisting of no characters
String buffer = null; // buffer for suspected middle 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;
buffer = "" + current;
}
else if ( state==2 && current <= space )
{
state = 2;
buffer += current;
}
else if ( state==2 && current > space )
{
state = 1;
outString += buffer + current;
}
}
return outString;
}
}
You may wish to improve the user interaction of this program by replacing
inString = args[0] with something
more elaborate.
Can command line arguments contain spaces?