Java Reference
In-Depth Information
Instance methods of StringBuffer
Below, we describe some methods of StringBuffer assuming that q is a
variable of that class. There are two constructors:
new StringBuffer(): = a new StringBuffer that contains "" .
new StringBuffer(p): = a new StringBuffer that contains String p .
Functions q.length , q.charAt() , q.substring , and q.toString have
their counterparts in class String and need no discussion.
The following procedure calls change q . We omit various restrictions on the
arguments of procedure calls; see the footnotes on lesson page 5-4 of the CD for
a full description, as well as examples.
q.setCharAt(i, c);
Change q[i] to character c .
q.append(x);
Append x to q . Arg. x can be of any primitive
type or class type; if not a String , it is
converted to a String and appended.
q.delete(h, k);
Delete substring q[h..k - 1] from q .
q.deleteCharAt(k) ;
Delete character q[k] from q .
q.insert(k, x);
Change q to q[0..k - 1] + x + q[k..] .
Convert x to a String , if necessary.
q.replace(h, k, x);
Replace q[h..k - 1] by String x .
q.reverse();
Reverse the characters of q , so it reads backward.
q.setLength(n) :
Set the length of q to n , either deleting a suffix or
appending null characters '\u0000' as necessary.
Java's use of StringBuffers
StringBuffers are actually used to implement operation catenation + . For
example, assuming that x is String variable, the statement
x= "a " + 12;
is compiled into the equivalent of:
x= new StringBuffer().append("a ").append(12).toString();
A StringBuffer is created, and strings are appended to it. Finally, the
StringBuffer is converted to a String , which is assigned to x .
Extracting an integer from a StringBuffer
At the end of Sec. 5.2.4, we developed a sequence of statements to remove
an unsigned integer from a string. In Fig. 5.2, we define a function that removes
and returns an unsigned integer from its StringBuffer parameter. We cannot
write a similar function with a String parameter because Strings are
immutable. This is indeed a situation where a StringBuffer should be used.
Functions trim and indexOf do not exist in StringBuffer , so we wrote
loops to find the index of the first nonblank and the index of the first blank.
See a footnote
on lesson page
5-4 to get this
function.
Search WWH ::




Custom Search