The String and StringBuffer Classes |
Theclass 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(); } }reverseIt
method uses StringBuffer'sappend()
method to add a character to the end of the destination string:dest
. 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 minimizing the number of times memory must be allocated for a StringBuffer by initializing its capacity to a reasonable first guess. For example, thereverseIt
method constructs the StringBuffer with an initial capacity equal to the length of the source string ensuring only one memory allocation fordest
.Using
append()
to add a character to the end of a StringBuffer is only one of StringBuffer's methods that allow you to append data to the end of a StringBuffer. There are severalappend()
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 takes place.Insertion
At times, you may want to insert data into the middle of a StringBuffer. You do this with one of StringBufffer'sinsert()
methods. This example illustrates how you would insert a string into a StringBuffer.This code snippet printsStringBuffer sb = new StringBuffer("Drink Java!"); sb.insert(6, "Hot "); System.out.println(sb.toString());With StringBuffer's manyDrink Hot Java!insert()
, 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 useappend()
.Set Character At
Another useful StringBuffer modifier issetCharAt()
which sets the character at a specific location in the StringBuffer.setCharAt()
is useful when you want to reuse a StringBuffer.
The String and StringBuffer Classes |