Trail: Essential Java Classes
|
Lesson: The String and StringBuffer Classes
|
|
Modifying StringBuffers
The reverseIt method uses StringBuffer's
append method to
add a character to the end of the destination string: dest.
class ReverseString {
public static String reverseIt(String source) {
int i, len = source.length();
StringBuffer dest = new StringBuffer(len);
for (i = (len - 1); i >= 0; i--) {
dest.append(source.charAt(i));
}
return dest.toString();
}
}
If the appended character causes the size of the StringBuffer to grow
beyond its current capacity, the StringBuffer allocates more memory.
Because memory allocation is a relatively expensive operation, you can make
your code more efficient by initializing a StringBuffer's capacity to a
reasonable first guess, thereby minimizing the number of times memory
must be allocated for it. For example, the reverseIt method
constructs the StringBuffer with an initial capacity equal to the length
of the source string, ensuring only one memory allocation for dest.
The version of the append method used in reverseIt
is only one of the StringBuffer methods that appends data to the end of a
StringBuffer. There are several append methods that append
data of various types, such as float, int, boolean,
and even Object, to the end of the StringBuffer. The data is
converted to a string before the append operation takes place.
Inserting Characters
At times, you may want to insert data into the middle of a StringBuffer.
You do this with one of StringBufffer's insert methods.
This example illustrates how you would insert a string into a StringBuffer:
StringBuffer sb = new StringBuffer("Drink Java!");
sb.insert(6, "Hot ");
System.out.println(sb.toString());
This code snippet prints:
Drink Hot Java!
With StringBuffer's many insert methods,
you specify the index before which you want the data inserted.
In the example, "Hot " needed to be inserted before the 'J'
in "Java". Indices begin at 0, so the index for 'J' is 6.
To insert data at the beginning of a StringBuffer, use an index of 0.
To add data at the end of a StringBuffer, use an index equal to the current
length of the StringBuffer or use append.
Setting Characters
Another useful StringBuffer modifier is setCharAt, which
replaces the character at a specific location in the StringBuffer
with the character specified in the argument list..
setCharAt is useful when you want to reuse a StringBuffer.
|